LintCode184: Largest Number

  1. Largest Number
    中文English
    Given a list of non negative integers, arrange them such that they form the largest number.

Example
Example 1:

Input:[1, 20, 23, 4, 8]
Output:“8423201”
Example 2:

Input:[4, 6, 65]
Output:“6654”
Challenge
Do it in O(nlogn) time complexity.

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

解法1:将integer转换成string来处理。关键是operator()的实现。
注意:

  1. a=259, b=2596这样的情况,b要排在a的前面。
    但a=259, b=2591这样的情况,b要排在a的后面。
  2. 前面有多个0的排除。如果是”000“,则直接返回”0“。
    代码如下:
struct cmp {
    bool operator() (int & a, int & b) {
        string str_a = to_string(a), str_b = to_string(b);
        int M = str_a.size(), N = str_b.size();
        
        if (M == N) return a > b;
        int minNum = min(M, N);
        
        for (int i = 0; i < minNum; ++i) {
            if (str_a[i] > str_b[i]) return true;
            else if (str_a[i] < str_b[i]) return false;
        }
        
        if (M == minNum) {
            return str_b[minNum] < str_a[0];
        } else {
            return str_a[minNum] > str_b[0];
        }
        
    }
} compare;

class Solution {
public:
    /**
     * @param nums: A list of non negative integers
     * @return: A string
     */
    string largestNumber(vector<int> &nums) {
        int N = nums.size();
        if (N == 0) return "";
        
        string result = "";
        sort(nums.begin(), nums.end(), compare);
        
        for (auto n : nums) {
            result = result + to_string(n);
        }

        int count0 = 0;
        for (int i = 0; i < N; ++i) {
            if (result[0] == '0') count0++;
        }
        
        if (count0 == N) return "0";
        if (count0 == 0) return result;
        return result.substr(count0);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值