Title Description
Enter an array of positive integers, combine all the numbers in the array into a number, and print the smallest of all the numbers that can be stitched together. For example, enter the array {3,32,321}, then print out the minimum number that these three numbers can be ranked as 321323.
Ideas:
Here to customize a comparison of the size of the function, compare two strings S1, S2 size, the first splicing them together, compare s1+s2, and s2+s1 that big, if s1+s2 big, that means S2 should be put in front, so according to this rule, S2 should be in front of S1.
It is important to note that there may be a numerical overflow, so it is converted into a string to handle.
Idea 1: direct solution with bubbling
1 Importjava.util.ArrayList;2 ImportJava.util.Comparator;3 Public classSolution {4 PublicString Printminnumber (int[] numbers) {5String res = "";6 for(inti = 0;i<numbers.length;i++){7 for(intj = 0;j<numbers.length-i-1;j++){8 if(Compare (numbers[j],numbers[j+1]) >0)9Swap (numbers,j,j+1);Ten } One } A for(inti=0;i<numbers.length;i++){ -Res+=numbers[i]+ ""; - } the returnRes; - } - Private voidSwapint[] A,intIintj) { - inttemp =A[i]; +A[i] =A[j]; -A[J] =temp; + } A Private intCompare (Integer s1,integer s2) { at return(s1+ "" +s2). CompareTo ((s2+ "" +s1)); - } -}
Idea 2: Using an already existing sort function in Java
1 Importjava.util.ArrayList;2 ImportJava.util.Comparator;3 Importjava.util.Collections;4 Public classSolution {5 PublicString Printminnumber (int[] numbers) {6String res = "";7arraylist<integer> num =NewArraylist<integer>();8 for(inti = 0;i<numbers.length;i++)9 Num.add (Numbers[i]);TenCollections.sort (NUM,NewComparator<integer>(){ One Public intCompare (Integer s1,integer s2) { A return(s1+ "" +s2). CompareTo ((s2+ "" +s1));} - }); - for(intj:num) { theRes+=j+ ""; - } - returnRes; - } + - +}
32 arrange the array into the smallest number