力扣179. 最大数(自定义排序)
https://leetcode-cn.com/problems/largest-number/
自定义排序
下面考虑输入数组 有相同数字开头 的情况,例如 [4,42][4,42] 和 [4,45][4,45]。
对于 [4,42][4,42],比较 442 > 424442>424,需要把 44 放在前面;
对于 [4,45][4,45],比较 445 < 454445<454,需要把 4545 放在前面。
sort(nums.begin(),nums.end(),[](const int &e1,const int &e2)
{
string s1=to_string(e1);
string s2=to_string(e2);
return s1+s2>s2+s1;
}
);
class Solution {
public:
string largestNumber(vector<int>& nums) {
string res;
sort(nums.begin(),nums.end(),[](const int &e1,const int &e2)
{
string s1=to_string(e1);
string s2=to_string(e2);
return s1+s2>s2+s1;
}
);
int i=0;
while(i!=nums.size()-1 && nums[i]==0)
{
i++;
}
for(;i<nums.size();i++)
{
res=res+to_string(nums[i]);
}
return res;
}
};