把数组排成最小的数(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));
    }
}

你可能感兴趣的:(剑指offer)