leetcode 179. 最大数(Largest Number)

题目描述:

给定一组非负整数,重新排列它们的顺序使之组成一个最大的整数。

示例 1:

输入: [10,2]
输出: 210

示例 2:

输入: [3,30,34,5,9]
输出: 9534330
说明: 输出结果可能非常大,所以你需要返回一个字符串而不是整数。

解法:

# define PR pair<string, int>

static bool cmp(const PR& pr1, const PR& pr2){
    string s1 = pr1.first;
    string s2 = pr2.first;
    return s1 + s2 >= s2 + s1;
}

class Solution {
public:
    string itoa(int num){
        string res = "";
        if(num == 0){
            return "0";
        }else{
            while(num != 0){
                res = char(num%10 + '0') + res;
                num /= 10;
            }
            return res;
        }
    }
     
    string largestNumber(vector<int>& nums) {
        vector<PR> lst;
        unordered_map<string, int> mp;
        for(int num : nums){
            string s = itoa(num);
            if(mp.find(s) == mp.end()){
                mp[s] = 1;
            }else{
                mp[s]++;
            }
        }
        for(auto it : mp){
            lst.push_back(it);
        }
        sort(lst.begin(), lst.end(), cmp);
        string res = "";
        for(PR pr : lst){
            string s = pr.first;
            int cnt = pr.second;
            for(int i = 0; i < cnt; i++){
                res += s;
            }
        }
        if(res[0] == '0'){
            return "0";
        }else{
            return res;
        }
    }
};

猜你喜欢

转载自www.cnblogs.com/zhanzq/p/10831848.html
今日推荐