给出一组非负整数,重新排列他们的顺序把他们组成一个最大的整数。
样例
样例 1:
输入:[1, 20, 23, 4, 8]
输出:"8423201"
样例 2:
输入:[4, 6, 65]
输出:"6654"
挑战
在 O(nlogn) 的时间复杂度内完成。
注意事项
最后的结果可能很大,所以我们返回一个字符串来代替这个整数。
思路:重写sort的排序函数,比较两个数合并后的字符串大小,以此排序,然后将排序后的数组拼接起来即可
注意:排序可能有“000000”的情况,这个时候,如果结果第一位是0的话,则返回0即可
class Solution {
public:
/**
* @param nums: A list of non negative integers
* @return: A string
*/
static bool cmp(const int &a,const int &b)
{
return to_string(a) + to_string(b) > to_string(b) + to_string(a);
}
string largestNumber(vector<int> &nums) {
// write your code here
sort(nums.begin(),nums.end(),cmp);
string res="";
for (int i = 0; i < nums.size(); i++) {
/* code */
res+=to_string(nums[i]);
}
return res[0]=='0'?"0":res;
}
};