Given a list of non negative integers, arrange them such that they form the largest number.
Example 1:
Input:[10,2]
Output: "210"
Example 2:
Input:[3,30,34,5,9]
Output: "9534330"
题目大意:
找出给出数组中int类型的数,能够排列成最大的十进制数。注:会出现全0
解题思路:
将int转成string
C++sort中比较函数为:
struct cmp{
bool operator()(const string& lhs, const string& rhs){
return lhs + rhs > rhs + lhs;
}
};
不用多解释了,就个这写了1个小时,丧:-(
class Solution {
private:
vector<string> c;
void helper(vector<int> tmp){
for(int i=0;i<tmp.size();i++){
int t = tmp[i];
string st;
if(t==0) st = '0';
while(t){
st += ('0'+(t%10));
t = t/10;
}
reverse(st.begin(), st.end());
c.push_back(st);
}
}
struct cmp{
bool operator()(const string& lhs, const string& rhs){
return lhs + rhs > rhs + lhs;
}
};
public:
string largestNumber(vector<int>& nums) {
helper(nums);
sort(c.begin(), c.end(), cmp());
string ans;
for(int i=0;i<c.size();i++){
ans += c[i];
}
if(ans[0]=='0') return "0";
return ans;
}
};