Given a list of non negative integers, arrange them such that they form the largest number.
For example, given [3, 30, 34, 5, 9]
, the largest formed number is 9534330
.
Note: The result may be very large, so you need to return a string instead of an integer
小技巧为排序中的比较函数,另外记住不能有=号
class Solution { public: static bool compareFunc(string &s1, string& s2) { return s1+s2 > s2+s1; } string largestNumber(vector<int>& nums) { string res; int n = nums.size(); vector<string> vecStr; for (int i = 0; i < n; i++) { vecStr.push_back(to_string(nums[i])); } sort(vecStr.begin(), vecStr.end(), compareFunc); if(vecStr[0] == "0") return "0"; for (int i = 0; i < n; i++) { res += vecStr[i]; } return res; } };