把数组排成最小的数

74 阅读1分钟

把数组排成最小的数

输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。

例如输入数组[3, 32, 321],则打印出这3个数字能排成的最小数字321323。
注意:输出数字的格式为字符串。

样例
输入:[3, 32, 321]
输出:321323

比较器

时间复杂度O(nlogn)

class Solution {
    public String printMinNumber(int[] nums) {
        int n = nums.length;
        String res = "";
        List<Integer> list = new ArrayList();
        for(int i = 0;i < nums.length;i++){
            list.add(nums[i]);
        }
        Collections.sort(list,new Comparator<Integer>(){
            @Override
            public int compare(Integer i1,Integer i2){
                String s1 = i1 + "" + i2;
                String s2 = i2 + "" + i1;
                return s1.compareTo(s2);
            }
        });
        for(int i : list){
            res += i;
        }
        return res;
    }
}