Topic
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.
My thoughts.
This problem is easy to think of is the sort, after the sorting as long as the number is stitched into a string on it. Here are two versions of the code, one is to implement the comparison and sorting, one is the use of collections this tool class sort method, need to rewrite the Compare method.
The code is as follows
PublicStringPrintminnumber(int[] numbers) {if(Numbers = =NULL|| Numbers.length==0)return ""; Mycomparator Mycomparator =New Mycomparator(); list<integer> list =NewArraylist<integer> (); for(inti:numbers) {list.Add(i); } collections.Sort(list, mycomparator); StringBuilder SB =NewStringBuilder (); for(Integer val:list) {sb.Append(Val); }returnSb.toString();}Private classMycomparatorImplementsComparator < Integer > {@Override Public int Compare(Integer O1, integer o2) {string S1 = string.valueOf(O1); String s2 = string.valueOf(O2); String str1 = s1+s2; String str2 = s2+s1;returnStr1.CompareTo(STR2); }}
PublicStringPrintminnumber(int[] numbers) {arraylist<arraylist<integer>> list =NewArraylist<arraylist<integer>> (); StringBuilder str =NewStringBuilder (); for(intI:numbers) {if(list.IsEmpty()) {arraylist<integer> innerlist =NewArraylist<integer> (); Innerlist.Add(i); List.Add(innerlist); }Else{Sortadd(list, i); }//System.out.println ("This round loop adds" + i); //For (arraylist<integer> innerlist:list) { //For (Integer it:innerlist) { //System.out.print (it); // } // } //System.out.println ();} for(arraylist<integer> innerlist:list) { for(Integer it:innerlist) {str.Append(it.toString()); } }returnStr.toString();} Public void Sortadd(arraylist< arraylist< Integer >> list,inti) { for(arraylist<integer> innerlist:list) {if(GetFirst(Innerlist.Get(0)) >GetFirst(i)) {arraylist<integer> Newinner =NewArraylist<integer> (); Newinner.Add(i); List.Add(list.indexOf(innerlist), Newinner);return; }Else if(GetFirst(Innerlist.Get(0)) ==GetFirst(i)) {String Newinsert = i +""; for(Integer it:innerlist) {String itstring = it.toString();intLength = Newinsert.length() > Itstring.length() ? Newinsert.length(): Itstring.length(); for(intj =0; J < length; J + +) {CharNewchar,itchar;if(J < Newinsert.length()) {Newchar = Newinsert.charAt(j); }Else{Newchar = Newinsert.charAt(0); }if(J < Itstring.length()) {Itchar = itstring.charAt(j); }Else{Itchar = itstring.charAt(0); }if(Newchar < Itchar) {innerlist.Add(Innerlist.indexOf(it), i);return; }}} innerlist.Add(i);return; }} arraylist<integer> Newinner =NewArraylist<integer> (); Newinner.Add(i); List.Add(Newinner);} Public int GetFirst(intN) { while(N/Ten!=0) n/=Ten;returnn;}
To rank the array into the smallest number