- Largest Number
中文English
Given a list of non negative integers, arrange them such that they form the largest number.
Example
Example 1:
Input:[1, 20, 23, 4, 8]
Output:“8423201”
Example 2:
Input:[4, 6, 65]
Output:“6654”
Challenge
Do it in O(nlogn) time complexity.
Notice
The result may be very large, so you need to return a string instead of an integer.
解法1:将integer转换成string来处理。关键是operator()的实现。
注意:
- a=259, b=2596这样的情况,b要排在a的前面。
但a=259, b=2591这样的情况,b要排在a的后面。 - 前面有多个0的排除。如果是”000“,则直接返回”0“。
代码如下:
struct cmp {
bool operator() (int & a, int & b) {
string str_a = to_string(a), str_b = to_string(b);
int M = str_a.size(), N = str_b.size();
if (M == N) return a > b;
int minNum = min(M, N);
for (int i = 0; i < minNum; ++i) {
if (str_a[i] > str_b[i]) return true;
else if (str_a[i] < str_b[i]) return false;
}
if (M == minNum) {
return str_b[minNum] < str_a[0];
} else {
return str_a[minNum] > str_b[0];
}
}
} compare;
class Solution {
public:
/**
* @param nums: A list of non negative integers
* @return: A string
*/
string largestNumber(vector<int> &nums) {
int N = nums.size();
if (N == 0) return "";
string result = "";
sort(nums.begin(), nums.end(), compare);
for (auto n : nums) {
result = result + to_string(n);
}
int count0 = 0;
for (int i = 0; i < N; ++i) {
if (result[0] == '0') count0++;
}
if (count0 == N) return "0";
if (count0 == 0) return result;
return result.substr(count0);
}
};
博客围绕LintCode中排列非负整数形成最大数的问题展开。给出示例输入输出,提出在O(nlogn)时间复杂度内解决的挑战,还指出结果可能很大需返回字符串。介绍解法是将整数转字符串处理,强调operator()实现及特殊情况处理,最后给出代码。
381

被折叠的 条评论
为什么被折叠?



