32.把數組排成最小的數
阿新 • • 發佈:2019-04-30
tor turn com str 代碼 正整數 比較 code 打印
題目描述:
??輸入一個正整數數組,把數組裏所有數字拼接起來排成一個數,打印能拼接出的所有數字中最小的一個。例如輸入數組{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; } }
32.把數組排成最小的數