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.
sort的妙用,但如下代码里为什么comp函数一定要是static的呢?
如果non-static,sort函数是其他class调用Solution的comp方法,即,
a.comp(b, c);
这需要三个参数;但是,sort的源码里并没有new出一个Solution类用于调用comp方法。
而如果声明为static,则只需要两个参数即可调用comp,所以需要声明为static。
stackoverflow上有详细解释:http://stackoverflow.com/questions/26131112/why-here-stdsort-requires-static-compare-function
class Solution {
public:
//此处为何是static,stackoverflow上有很好的分析
static bool comp(string str1, string str2) {
return str1+str2 > str2+str1;
}
string largestNumber(vector<int>& nums) {
vector<string> sv;
int i=0;
while(i<nums.size()) {
sv.push_back(std::to_string(nums[i++]));
}
std::sort(sv.begin(), sv.end(), comp);
string sum;
int j=0;
while(j<sv.size()) {
sum += sv[j++];
}
//针对sum以0开头的特殊处理,分为"0"和 "0002"两种情况
while(sum[0]=='0' && sum.size()>1) {
sum.erase(0,1);
}
return sum;
}
};