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.
Subscribe to see which companies asked this question
本题的关键在于写出sort函数的自定义排序方法,参考[C++]LeetCode: 128 Largest Number (自定义比较函数排序) 写的方法,非常的通俗易懂。
对于sort的自定义比较函数
static bool cmp(string a,string b)
{
return a+b>b+a;
}
当需要a排前面,b排后面返回true,若需要b排前面,a排后面则需要返回false.显然上面是要a+b比b+a大时把a排前面。
bool less_int(int a,int b){
return b<a;
}
显然上面是a>b时,a排前面。即按大到小的排。bool less_int(int a,int b){
return b>a;
}
按小到大的排。代码:
class Solution {
public:
static bool cmp(string a,string b)
{
return a+b>b+a;
}
string largestNumber(vector<int>& nums) {
vector<string> v1;
for(auto p:nums)
v1.push_back(to_string(p));
sort(v1.begin(),v1.end(),cmp);
string result="";
for(auto p:v1)
result+=p;
if(result[0]=='0') return "0";
return result;
}
};