题目描述
Given a list of non negative integers, arrange them such that they form the largest number.
Example1:
Input: [10,2] Output: "210"
Example2:
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.
解题思路
- a + b > b + a,这样的话,一定a是在b前面的
- 重写比较运算符,然后排序即可
class Solution {
public:
static bool cmp(string& a, string& b){
return a + b > b + a;
}
string largestNumber(vector<int>& nums) {
vector<string> v;
for(auto& i : nums){
v.push_back(to_string(i));
}
sort(v.begin(), v.end(), cmp);
string res;
for(int i = 0; i < v.size(); i++){
if(i == 0 && v[i] == "0"){
return "0";
}
res += v[i];
}
return res;
}
};