题目描述:
Given a list of non negative integers, arrange them such that they form the largest number.
Notice
The result may be very large, so you need to return a string instead of an integer.
Example
Given [1, 20, 23, 4, 8]
, the largest formed number is 8423201
.
Challenge
题目思路:
Do it in O(nlogn) time complexity.
这题的关键在于怎么定义compare函数,定义好了,直接把string按照排序好的vector写好就好了。
compare函数我是这么定义的(由大到小排序):
1. 从两个string a和b的头开始找,如果发现a[idx_a] > b[idx_b],就返回true
2. 如果a或者b的任何一个string已经找完,比如,b已经找完,但是a还没找完,不能简单的根据找完和没找完来判断(反例就是[2,20]和[2,23])。应该把a没找完的char跟b的最后一个char比较:如果char a > char b end,那么还是a大([2,23])的例子,23应该比2大;反之就是[2,20]的例子,2比20大。对于a已经找完,但是b还没找完的情况也是类似的判断。
Mycode(AC = 15ms):
class Solution {
public:
/**
*@param num: A list of non negative integers
*@return: A string
*/
string largestNumber(vector<int> &num) {
// write your code here
if (num.size() == 0) return "0";
// define the compare function:
// if a[idx_a] > b[idx_b], then a > b
// after loop,
// if a is longer than b, then compare a[idx_a++] and b[idx_b - 1]
// if b is longer than a, then compare a[idx_a - 1] and b[idx_b++]
auto comp = [] (const string&a, const string&b) {
int idx_a = 0, idx_b = 0;
while (idx_a < a.length() && idx_b < b.length()) {
if (a[idx_a] > b[idx_b]) {
return true;
}
else if (a[idx_a] < b[idx_b]) {
return false;
}
else {
idx_a++; idx_b++;
}
}
//e.g., 2 compare with 23/20
while (idx_a < a.length()) {
if (a[idx_a] > b[idx_b - 1]) {
return true;
}
else if (a[idx_a] < b[idx_b - 1]){
return false;
}
idx_a++;
}
while (idx_b < b.length()) {
if (b[idx_b] < a[idx_a - 1]) {
return true;
}
else if (b[idx_b] > a[idx_a - 1]) {
return false;
}
idx_b++;
}
return false;
};
// change the int to string, then do string sort
vector<string> str_num(num.size(), "");
for (int i = 0; i < str_num.size(); i++) {
str_num[i] = to_string(num[i]);
}
sort(str_num.begin(), str_num.end(), comp);
string ans = "";
for (int i = 0; i < str_num.size(); i++) {
ans += str_num[i];
}
// remove '0' at beginning
while (ans.length() > 1 && ans[0] == '0') {
ans = ans.substr(1);
}
return ans;
}
};