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

【leetcode】Largest Number

时间:2015-02-01 20:28:26      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

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.

Credits:

Special thanks to @ts for adding this problem and creating all test cases.


bool myfunction(string s1, string s2){
    string s3 = s1 + s2;
    string s4 = s2 + s1;
    
    return s3 > s4;
}

class Solution {
public:
    string largestNumber(vector<int> &num) {
        //convert vector<int> to vector<string>
        int N = num.size();
        vector<string> strs;
        for(int i = 0; i < N; i++){
            stringstream ss;
            ss << num[i];
            strs.push_back(ss.str());
        }
        
        //sort strs
        sort(strs.begin(), strs.end(), myfunction);
        
        //concat strs together, and remove all "0"s 
        string s;
        int i = 0;
        while(i < N && strs[i] == "0"){
            i++;
        }
        while(i < N){
            s += strs[i];
            i++;
        }

        if(s == ""){
            s = "0";
        }
        return s;
    } 
};


【leetcode】Largest Number

标签:

原文地址:http://blog.csdn.net/tuantuanls/article/details/43374267

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