题目:
Given a list of non-negative integers nums, arrange them such that they form the largest number.
Note: The result may be very large, so you need to return a string instead of an integer.
思路:
将ab和ba进行比较,以此来排序nums数组。
代码实现:
class Solution {
public:
static int cmp(int &a, int &b){
string t1 = to_string(a) + to_string(b);
string t2 = to_string(b) + to_string(a);
return t1 > t2;
}
string largestNumber(vector<int>& nums) {
if (nums.size() == 0) return "";
sort(nums.begin(), nums.end(), Solution::cmp);
string ans = "";
for (int i = 0; i < nums.size(); ++i){
ans += to_string(nums[i]);
}
return ans[0] == '0'? "0" : ans;
}
};