Given a list of non negative integers, arrange them such that they form the largest number.
Example 1:
Input:[10,2]
Output: "210"
Example 2:
Input:[3,30,34,5,9]
Output: "9534330"
Note: The result may be very large, so you need to return a string instead of an integer.
思路:将数组按照拼接结果排序(自定义)。然后考虑排序后数组首字母为0的情况。逐个对排序后数组元素相加即可。
class Solution { public: static bool cmp(int a, int b) { string s1 = to_string(a); string s2 = to_string(b); return s1 + s2 > s2 + s1; } string largestNumber(vector<int>& nums) { string res; if (nums.empty()) return res; sort(nums.begin(), nums.end(), cmp); int i = 0; while (nums[i] == 0 && i < nums.size()) i++; if (i == nums.size()) return "0"; for (int j = i; j < nums.size(); ++j) res += to_string(nums[j]); return res; } };