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.
基本思路:
先进行排序。排序的比较函数很关键,两个数前后串接起来,谁在前面形成较大的数,则该数排在前面。
另外要注意的边界情况是: 当数全部为0时,需要返回为"0",而不是"000"。即只需要返回一个0.
class Solution {
public:
string largestNumber(vector<int>& nums) {
sort(nums.begin(), nums.end(), [](int a, int b) { return to_string(a)+to_string(b) > to_string(b)+to_string(a);});
if (!nums.empty() && !nums[0])
return "0";
string ans;
for (auto i: nums) {
ans += to_string(i);
}
return ans;
}
};