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.
1.我的解答
也是看了剑指offer上面的解答。
这里出现了两个问题:
1. 对比较函数compare要使其为static。(我也不知道为什么要这样,希望懂得人能够帮忙解答)
2. 若给出的是[0,0],则我当时返回的是字符串“00”,而正确需返回“0”.因此这里需要对结果进行去掉首部的0的操作。
具体代码如下:
class Solution {
public:
static bool compares(const string s1, const string s2){
string t1 = s1+s2;
string t2 = s2+s1;
return t1 > t2;
}
string largestNumber(vector<int>& nums) {
string res;
if(nums.size() == 0) return res;
int len = nums.size();
vector<string> s(nums.size());
for(int i = 0; i < nums.size(); i++){
string t = to_string(nums[i]);
s[i] = t;
}
sort(s.begin(), s.end(), compares);
bool atfirst = true;
for(int j = 0; j < s.size(); j++){
if(s[j] == "0" && atfirst)
continue;
else{
if(atfirst) atfirst = false;
res += s[j];
}
}
if(res.size() == 0) res = "0";
return res;
}
};
2.下面是别人的代码
他的sort函数中用lamda来写compare操作
class Solution {
public:
string largestNumber(vector<int> &num) {
vector<string> arr;
for(auto i:num)
arr.push_back(to_string(i));
sort(begin(arr), end(arr), [](string &s1, string &s2){ return s1+s2>s2+s1; });
string res;
for(auto s:arr)
res+=s;
while(res[0]=='0' && res.length()>1)
res.erase(0,1);
return res;
}
};