1,题目要求
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"
Note:
The result may be very large, so you need to return a string instead of an integer.
给定一个非负整数列表,将它们排列成最大数字。
注意:
结果可能非常大,因此您需要返回一个字符串而不是整数。
2,题目思路
对于这道题,要求将一个给定的非负整数表排列成一个最大数字。
在排列上,我们需要返回的是一个字符串,因此,在构建时,我们也要以字符串的形式进行返回。
因此,在进行字符的排序和选择上,我们可以定义一个比较规则:
对于s1和s2,如果s1+s2 > s2+s1,就返回true。换句话说,排序按照使得两个字符串相加较大的次序进行排列。
最后,还需要注意的是,给定的数组可能是全0的情况,如果不做单独的处理,会有一串0的结果,而正确的答案是只有一个0,因此,这是我们需要对这种情况做单独的判断,直接返回"0"即可。
3,代码实现
static auto speedup = [](){
ios::sync_with_stdio(false);
cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
string largestNumber(vector<int>& nums) {
vector<string> sortedNums;
for(auto &i : nums)
sortedNums.push_back(to_string(i));
sort(sortedNums.begin(), sortedNums.end(), [](string &s1, string &s2){return s1+s2 > s2+s1;});
string res = "";
for(auto &s : sortedNums)
res += s;
if(res[0] == '0' && res.size() >1)
return "0";
return res;
}
};