179. Largest Number

问题描述:

Given a list of non negative integers, arrange them such that they form the largest number.

Example 1:

Input: [10,2]
Output: "210"

Example 2:

Input: [3,30,34,5,9]
Output: "9534330"

Note: The result may be very large, so you need to return a string instead of an integer.

 

解题思路:

重写比较器,将放在前面能够形成较大数字的数字放在前面。

 

代码:

class Solution {
public:
    string largestNumber(vector<int>& nums) {
        vector<string> str;
        bool allZero = true;
        for(int n : nums){
            if(n != 0)
                allZero = false;
            str.push_back(to_string(n));
        }
        if(allZero)
            return "0";
        sort(str.begin(), str.end(), [](string &a, string &b){
            return a+b > b+a; 
        });
        string ret;
        for(string s: str){
            ret += s;
        }
        return ret;
    }
};

 

posted @ 2018-06-27 01:18  妖域大都督  阅读(99)  评论(0编辑  收藏  举报