zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    作业
    作业
    [转]C语言指针 之 函数指针
    iOS 隐私政策
    微信小程序成长记录(一)
    ios 用信号量控制多个异步网络请求
    ios 利用cocapods创建私有库
    ios 整理获取设备相关信息
    ios_scrollView顶部图片下拉放大
    ios 在项目中使用文字ttf文件
  • 原文地址:https://www.cnblogs.com/z1141000271/p/12777937.html
Copyright © 2011-2022 走看看