leetcode 179 最大数(贪心)

题目描述:

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

题解:

  为了组成最大的整数,我们希望把较大的数安排在前面,如果仅按降序排序,有相同的开头数字的时候会出现问题。比方说,样例 $[3,30,34,5,9]$ 按降序排序得到的数字是$95343303$,然而交换$3$和$30$的位置可以得到正确答案 $95430330$ 。因此,每一对数在排序的比较过程中,我们比较两种连接顺序哪一种更好

AC代码:

  

class Solution {
public:
    string del(int x)
    {
        string res = "";
        if(x == 0) return "0";
        while(x)
        {
            res += (x%10+'0');
            x /= 10;
        }
        reverse(res.begin(),res.end());
        return res;
    }
    static bool cmp(string a,string b)
    {
        string t1 = a+b;
        string t2 = b+a;
        return t1 > t2;
    }
    string largestNumber(vector<int>& nums) {
        vector<string> tmp;
        for(auto &num:nums)
        {
            string t = del(num);
            tmp.push_back(t);
        }
        sort(tmp.begin(),tmp.end(),cmp);
        string ans="";
        if(tmp[0] == "0" && tmp[tmp.size()-1] == "0") return "0";
        for(auto & t:tmp) ans+=t;
        return ans;
    }
};
原文地址:https://www.cnblogs.com/z1141000271/p/12777937.html