32.把数组排成最小的数

题目描述:

  输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。

思路分析:

  要想将数组里所有的数拼起来排成一个数,还得是最小的,那么我们在拼接的过程中需要比较的是当两个数往一块拼的时候,“Integer1“+“Integer2”和“Integer2“+“Integer1”,谁小。我们实现的方法时对排序函数的compare方法重写。

代码:

import java.util.*;
/*
要想将数组里所有的数拼起来排成一个数,还得是最小的,那么我们在拼接的过程中
需要比较的是当两个数往一块拼的时候,“Integer1“+“Integer2”和“Integer2“+“Integer1”
谁小。
*/
public class Solution {
    public String PrintMinNumber(int [] numbers) {
        String res="";
        if(numbers.length==0||numbers==null)
            return res;
        ArrayList<Integer>list=new ArrayList<>();
        for(int i=0;i<numbers.length;i++){
            list.add(numbers[i]);
        }
        Collections.sort(list,new Comparator<Integer>(){
            @Override
            public int compare(Integer num1,Integer num2){
                String S1=num1+""+num2;
                String S2=num2+""+num1;
                return S1.compareTo(S2);
            } 
        });
        for(int num:list)
            res=res+num;
        return res;

    }
}
原文地址:https://www.cnblogs.com/yjxyy/p/10797576.html