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.
最开始感觉是桶排序,不过数字之间的比较有些繁琐,主要是包含的情况。看多余的数字跟第一个数字的大小关系?貌似也不是这么简单。比如:31, 3133,最大组合应该是3133-31;但31, 3130,最大的组合是31-3130。反正没搞明白。
退而求其次,直接排序吧,焦点放在排序的比较函数上。这就比较简单了。需要注意都是0的特殊情况。
bool myCompare(const string& s1, const string& s2) {
return (s1 + s2 > s2 + s1);
}
class Solution {
public:
string largestNumber(vector<int> &num) {
vector<string> candidates;
for (int i = 0; i < num.size(); ++i) {
candidates.push_back(to_string(num[i]));
}
sort(candidates.begin(), candidates.end(), myCompare);
string result;
for (int i = 0; i < candidates.size(); ++i) {
result.append(candidates[i]);
}
if (!result.empty() && result[0] == '0') {
result.resize(1);
}
return result;
}
};