#379 Reorder array to construct the minimum number

题目描述:

 This problem is in a contest:  Career Fair Warm Up I . Submit your code and see your ranking!

Construct minimum number by reordering a given non-negative integer array. Arrange them such that they form the minimum number.

 Notice

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

Example

Given [3, 32, 321], there are 6 possible numbers can be constructed by reordering the array:

3+32+321=332321
3+321+32=332132
32+3+321=323321
32+321+3=323213
321+3+32=321332
321+32+3=321323

So after reordering, the minimum number is 321323, and return it.

Challenge 

Do it in O(nlogn) time complexity.

题目思路:

这题和#184 largest number一毛一样,需要注意的是sort function里一定要记得加comp这个argument,否则怎么调都不对(因为comp根本没起作用)。

Mycode(AC = 15ms):

class Solution {
public:
    /**
     * @param nums n non-negative integer array
     * @return a string
     */
    string minNumber(vector<int>& nums) {
        // Write your code here
        auto comp = [](const string& a, const string& b) {
            int la = 0, lb = 0;
            while (la < a.length() && lb < b.length()) {
                if (a[la] < b[lb]) {
                    return true;
                }
                else if (a[la] > b[lb]) {
                    return false;
                }
                la++; lb++;
            }
            
            while (la < a.length()) {
                if (a[la] < b[lb - 1]) {
                    return true;
                }
                else if (a[la] > b[lb - 1]) {
                    return false;
                }
                la++;
            }
            
            while (lb < b.length()) {
                if (b[lb] < a[la - 1]) {
                    return false;
                }
                else if (b[lb] > a[la - 1]) {
                    return true;
                }
                lb++;
            }
            
            return false;
        };
        
        vector<string> str_nums(nums.size(), "");
        for (int i = 0; i < nums.size(); i++) {
            str_nums[i] = to_string(nums[i]);
        }
        
        sort(str_nums.begin(), str_nums.end(), comp);
        
        string ans = "";
        for (int i = 0; i < str_nums.size(); i++) {
            ans += str_nums[i];
        }
        
        while (ans.length() > 1 && ans[0] == '0') {
            ans = ans.substr(1);
        }
        
        return ans;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值