• lintcode-184-最大数


    184-最大数

    给出一组非负整数,重新排列他们的顺序把他们组成一个最大的整数。

    注意事项

    最后的结果可能很大,所以我们返回一个字符串来代替这个整数。

    样例

    给出 [1, 20, 23, 4, 8],返回组合最大的整数应为8423201。

    挑战

    在 O(nlogn) 的时间复杂度内完成。

    标签

    排序

    思路

    主体操作就是对 num 排序,要求在 O(nlogn) 的时间复杂度内完成,所以使用快排,即 sort() 函数,这里需要自定义比较函数 cmp
    在比较 2 个 int 型数据时,将其转换成 string 更加方便,比较思路为:

    • 若 a 与 b 中,a[i] > b[i],则 a > b (如 2345 < 245)

    • 若 a 与 b 中,a.size() < b.size() 且 a[i] = b[i],则只需比较 b[a.size()] 与 b[0]

      - 若 b[a.size()] > b[0],则 a < b (如 2221 < 222)
      - 否则,则 a > b (如 2224 > 222)
      

    code

    class Solution {
    public:
        /**
         *@param num: A list of non negative integers
         *@return: A string
         */
        
        string largestNumber(vector<int> &num) {
            // write your code here
            int size = num.size();
            if (size <= 0) {
                return string("");
            }
    
            sort(num.begin(), num.end(), cmp);
            string result;
            if (num[0] == 0) {
                result = "0";
                return result;
            }
            for (int i = 0; i < num.size(); i++) {
                char temp[50];
                sprintf(temp, "%d", num[i]);
                result += temp;
            }
            return result;
        }
    
        static bool cmp(int a, int b) {
            char temp[50];
            sprintf(temp, "%d", a);
            string stra = temp;
            sprintf(temp, "%d", b);
            string strb = temp;
    
            for (int i = 0; i < stra.size() && i < strb.size(); i++) {
                if (stra[i] > strb[i]) {
                    return true;
                }
                else if (stra[i] < strb[i]) {
                    return false;
                }
            }
            if (stra.size() < strb.size()) {
                return strb[stra.size()] > strb[0] ? false : true;
            }
            if (stra.size() > strb.size()) {
                return stra[strb.size()] > stra[0] ? true : false;
            }
            return false;
        }
    };
    
  • 相关阅读:
    !function() {}()
    element.dataset API
    正则匹配 数字和英文状态下的逗号
    《vim实用技巧》读书笔记
    ajax分页
    smarty分页类
    数组排序
    数组大类
    自动刷新价格
    简单购物车
  • 原文地址:https://www.cnblogs.com/libaoquan/p/7286936.html
Copyright © 2020-2023  润新知