"title" Enter an array of positive integers, combining all the numbers in the array into a number, and printing the smallest of all the numbers that can be stitched together.
* For example, input array {3,32,321}, the smallest number that can be printed out of these three numbers is 321323.
"Idea" 1 first converts an array of integers into a string array str;
2 Write a custom sort comparator to sort str. Results obtained after sorting 321,32,3 (<)
Sorting rules: Ab<ba a<b;
Ab>ba a>b;
Ab=ba a=b
3 Get sorted results.
Custom sort: int compare(t O1, t O2): compares the two parameters used to sort. Returns a negative integer, 0, or a positive integer, respectively, based on the first parameter less than, equal to, or greater than the second parameter.
1 PackageCom.exe11.offer;2 3 Importjava.util.Arrays;4 ImportJava.util.Comparator;5 6 /**7 * "title" Enter an array of positive integers, combining all the numbers in the array into a number, and printing the smallest of all the numbers that can be stitched together. 8 * For example, input array {3,32,321}, the smallest number that can be printed out of these three numbers is 321323. 9 * "idea" 1 first converts an array of integers into a string array str;Ten * 2 Write a custom sort comparator to sort str. Results obtained after sorting 321,32,3 (<) One * Sorting rules: Ab<ba a<b; A * Ab>ba a>b; - * Ab=ba a=b - * 3 get sorted after results. the * - * @authorWGS - * - */ + Public classPrintminnumberofarray { - PublicString Printminnumber (int[] numbers) { + if(numbers==NULL|| Numbers.length<=0) A return NULL; at -StringBuilder sb=NewStringBuilder (); -String[] Str=NewString[numbers.length]; - //1 Conversion - for(inti=0;i<numbers.length;i++){ -Str[i]=numbers[i]+ ""; in } - //2 Write a custom sort toComparator com=NewComparator<string>(){ + @Override - Public intCompare (String O1, String O2) { the return(O1+O2). CompareTo (o2+O1); * } $ };Panax Notoginseng //3 Sorting str - arrays.sort (str, COM); the //4 Get the sorted number + for(inti=0;i<str.length;i++){ A sb.append (Str[i]); the } + returnsb.tostring (); - } $ $ Public Static voidMain (string[] args) { -Printminnumberofarray p=NewPrintminnumberofarray (); - //int[] Nums=new int[]{3,32,321}; the int[] nums=New int[]{1,12,23,311}; -String s=P.printminnumber (nums);Wuyi System.out.println (s); the } -}
The sword refers to the offer series---the array into the smallest number