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.
本题比较类似于基数排序的第一步,当首位相同时,我们不需要从第二位开始逐位比较
class Comp
{
public:
bool operator()(const string& s1,const string& s2)
{
return s1+s2 > s2+s1;
}
};
class Solution {
public:
string largestNumber(vector<int>& nums) {
vector<string> strs;
for(int num:nums)
{
strs.push_back(to_string(num));
}
sort(strs.begin(),strs.end(),Comp());
string res;
if(strs[0][0]=='0') return "0";
for(string& s:strs)
res+=s;
return res;
}
};
转化为string之后,直接相加比较两个字符串谁打谁小。
summary
- 比较两个数字字符串谁大谁小的办法