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.
方法1:
思路:
这里要对数组进行排序,但是这个序既不是最大序也不是最小序,而是自定义的一个cmp,最终目的是找出"ab" 和“ba” 谁更大就把a/b排在前面。也可以用structure来写。
易错点
- 这个cmp写成s+t >= t +s 就不太行的样子。[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]会产生heap overflow为什么?
- 如果结果是“000000”,需要返回”0“。通过检查第一个字符是否是‘0’来完成。
- 直接全部变为string再传给comparator更快一点,否则要做很多边conversion。
//13ms
struct {
bool operator()(string a, string b)
{
string c1 = a + b;
string c2 = b + a;
return c1 > c2;
}
} compareDigits;
class Solution {
public:
string largestNumber(vector<int> &num) {
if (num.size() == 0) return "";
vector<string> num_str;
for (int i = 0; i < num.size(); ++i) {
num_str.push_back(to_string(num[i]));
}
std::sort(num_str.begin(), num_str.end(), compareDigits);
string res1 = "";
for (int i = 0; i < num_str.size(); ++i)
res1 += num_str[i];
if (res1[0] == '0')
return "0";
else
return res1;
}
};