首页 > 其他 > 详细

LeetCode[Sort]: Largest Number

时间:2015-02-17 21:07:00      阅读:348      评论:0      收藏:0      [点我收藏+]

LeetCode[Sort]: 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 is 9534330.
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

原文:http://blog.csdn.net/chfe007/article/details/43867315

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!