To arrange the array into the smallest number of questions.
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
- The number of two int can be larger, overflow, we can use a string to represent, handle the large number of problems
- Convert a number to a string, and then compare the size of the string, where the size refers to: if STR1+STR2 > Str2+str1, then str1 > str2, we need to redefine a compare function
- In fact, the final connection size and string comparison of the size of the rules are the same.
Code
Import Java.util.ArrayList;public class Solution {publicString printminnumber (int [] numbers) {string[] Numstr = newstring[numbers.length];for (int i =0; i < numbers.length; i++) {Numstr[i] =String.valueof (Numbers[i]);}Selectsort (NUMSTR);StringBuilderSTRB = newStringBuilder (); for (int j =0; J < Numstr.length; J + +) {Strb.append (Numstr[j]);} ReturnStrb.tostring (); }public int Comparestr (StringSTR1,StringSTR2) {StringBuilder SB1 = newStringBuilder ();StringBuilder SB2 = newStringBuilder (); Sb1.append (STR1); Sb1.append (STR2); Sb2.append (STR2); Sb2.append (STR1); return sb1.tostring (). CompareTo (Sb2.tostring ());} public voidselectsort (string[] data) {for (int i = 0; for (int j = Span class= "Hljs-preprocessor" >data.length-1; J >i; j--) { Span class= "Hljs-preprocessor" >if (comparestr (data[j], data[k]) < 0) k = J;} string temp = data[i] data[i] = data[k] data[k] = Temp;}}
Line up the array to the smallest number-the sword refers to the offer