标签:sort leetcode 算法 largest number
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 is9534330
.
Note: The result may be very large, so you need to return a string instead of an integer.
这个题目Discuss上有一个非常巧妙的方法来解决:https://oj.leetcode.com/discuss/21683/a-simple-c-solution
理解起来也非常容易,直接贴上代码吧:
string largestNumber(vector<int> &num) {
vector<string> strNum;
for (auto i : num)
strNum.push_back(to_string(i));
sort(begin(strNum), end(strNum), [](string &s1, string &s2){ return s1+s2>s2+s1; });
string result;
for (auto s : strNum)
result += s;
while (result[0] == ‘0‘ && result.size() > 1)
result.erase(0, 1);
return result;
}
这里需要注意sort函数的用法。
这种解法的时间性能表现如下图所示:
LeetCode[Sort]: Largest Number
标签:sort leetcode 算法 largest number
原文地址:http://blog.csdn.net/chfe007/article/details/43867315