码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】179. Largest Number

时间:2016-08-13 12:35:32      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:

Description:

  For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.

Analysis:

  The problem can be solved by sorting. It‘s reallllllllllllllllllllllllllllllllllllllllllly a tallent and brilliant idea to give a compare function like "return s1 + s2 > s2 + s1". Which converts complication to easiness. OMg...

Code:

bool cmp(const string &a, const string &b){
    return a + b > b + a;
}
class Solution {
public:
    string int2String(int n){
        string ret = "";
        if(n == 0) return "0";
        while(n){
            ret += 0 + (n % 10);
            n /= 10;
        }
        for(int i = 0; i < ret.length() / 2; i ++)
            swap(ret[i], ret[ret.length() - i - 1]);
        return ret;
    }

    string largestNumber(vector<int>& nums) {
        vector<string>rec;
        for(int i = 0; i < nums.size(); i ++){
            string str = int2String(nums[i]);
            rec.push_back(str);
        }
        sort(rec.begin(), rec.end(), cmp);
        string ans = "";
        for(int i = 0; i < rec.size(); i ++){
            ans += rec[i];
        }
        while(ans[0] == 0 && ans.length() > 1){
            return "0";
        }
        return ans;
    }
};

Using some new features in c++11:

1. Anonymous function: lambda used in cmp(compare function)

2. to_string(int) : returns a string.

3. auto

Learn more about those new features about c++11.

    string largestNumber(vector<int>& nums) {
        vector<string>rec;
        for(auto i : nums){
            rec.push_back(to_string(i));
        }
        sort(rec.begin(), rec.end(), [](const string &s1, const string &s2){ return s1 + s2 > s2 + s1;});
        string ans = "";
        for(auto s : rec){
            ans += s;
        }
        while(ans[0] == 0 && ans.length() > 1){
            return "0";
        }
        return ans;
    }

 

 

  

【LeetCode】179. Largest Number

标签:

原文地址:http://www.cnblogs.com/luntai/p/5767647.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!