把数组排成最小的数(Java实现)


import java.util.Arrays;
import java.util.Comparator;

public class E45SplicingToBeMin {
    //将数组中的数字拼接成最新小的数字

    public static String splicing(int[] numbers, int length){
        if (numbers == null || length <= 0)
            return null;
        //复制numbers
        Integer[] intNumbers = new Integer[length];
        for (int i = 0; i < length; i ++){
            intNumbers[i] = numbers[i];
        }
        //按指定比较器将数组排序
        Arrays.sort(intNumbers, new splicingComparator());
        //得到拼接的字符串
        return splicing(intNumbers);
    }

    private static String splicing(Integer[] numbers){
        //得到最小的拼接结果
        StringBuilder builder = new StringBuilder();
        for (int number : numbers)
            builder.append(number);
        return builder.toString();
    }

    static class splicingComparator implements Comparator<Integer>{
        //定义比较器,当mn>nm时,m>n
        @Override
        public int compare(Integer number1, Integer number2) {
            char[] splicing1 = (number1.toString() + number2.toString()).toCharArray();
            char[] splicing2 = (number2.toString() + number1.toString()).toCharArray();
            for (int i = 0; i < splicing1.length; i ++){
                if (splicing1[i] > splicing2[i])
                    return 1;
                else if (splicing1[i] < splicing2[i])
                    return -1;
            }
            return 0;
        }
    }

    //测试用例
    public static void main(String[] args){
        int[] numbers = {3, 32, 321};
        System.out.println(E45SplicingToBeMin.splicing(numbers, 3));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值