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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
思路:定义一种新的排序规则,如果ab>ba,那么a>b。a的优先级更高。
这种排序规则可以证明具有严格弱序。(传递性,自反性)
特别注意:ab>ba的时候最好不要采用数值比较(如果数据是int的话,当两个int很大时,int+int会非常大,甚至高过long long。
ab>ba时通过string处理。
还有当数组中全为零的时候,直接返回零。
compare必须定义为static型。
class Solution {
public:
string largestNumber(vector<int>& nums) {
string ret;
sort(nums.begin(),nums.end(),compare);
for(int i=0;i<nums.size();++i){
ret+=to_string(nums[i]);
}
if(ret[0]=='0')
return "0";
return ret;
}
static bool compare(const int &m,const int &n){
return to_string(m)+to_string(n)>to_string(n)+to_string(m);
}
};
更精简的代码用lambda表达式:
class Solution {
public:
string largestNumber(vector<int>& nums) {
string ret;
sort(nums.begin(),nums.end(),
[](const int &m,const int&n){
return to_string(m)+to_string(n)>to_string(n)+to_string(m);});
for(int i=0;i<nums.size();++i){
ret+=to_string(nums[i]);
}
if(ret[0]=='0') //for the case nums are all zeros
return "0";
return ret;
}
};