Reorder array to construct the minimum number 解题报告

Reorder array to construct the minimum number

Description

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.

实现思路

这道题关键在于字符串两两之间的大小比较以及排序算法。
这里排序算法用Java底层用归并实现的Arrays.sort,能将排序的时间复杂度控制在O(n*lnon)。
对于字符串的两两比较,按照我们这道题的思路,我们需要比较的是两两字符串s1,s2拼接是s1拼s2还是s2拼s1大,根据这句话,我们就可以直接通过比较s1+s2和s2+s1的字符序大小来得到我们的结果。
因为是要求最小的数,所以可能0会出现在最后拼接成的字符串最前面,我们需要把前导0去掉。

/**public class Solution {
    /**
     * @param nums n non-negative integer array
     * @return a string
     */
    public String minNumber(int[] nums) {
        int length = nums.length;
        String[] numstrs = new String[length];
        for (int i = 0; i < length; i++) {
            numstrs[i] = String.valueOf(nums[i]);
        }
        Arrays.sort(numstrs,new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return (o1+o2).compareTo(o2+o1);
            }

        });
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            sb.append(numstrs[i]);
        }
        while(sb.length() > 1){
            if(sb.charAt(0) == '0'){
                sb.deleteCharAt(0);
            }else{
                break;
            }
        }
        return sb.toString();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值