Given a list of non negative integers, arrange them such that they form the largest number.
For example, given [3, 30, 34, 5, 9] , the largest formed number is 9534330 .
Note:the result May is very large, so you need to return a string instead of an integer.
This topic took a lot of time at first, and the train of thought is not good. Converts a number to a string, allowing strings of different lengths to be compared from left to right by character. But if a string is another prefix, even if the extra string is compared to the first character, there are still a lot of things to deal with.
The simplest way to do this is to compare s1+s2 and s2+s1 when comparing two strings S1 and S2. Note that there is a special case where the combined string starts at 0 and needs to be removed from the beginning of the 0.
Class Stringcomparator implements comparator<string> {@Overridepublic int compare (string s1, string s2) {string S12 = s1 + s2; String S21 = s2 + s1;return (int) (Long.parselong (S12)-Long.parselong (S21));}} Public String largestnumber (int[] num) {StringBuilder sb = new StringBuilder (); list<string> numstr = new arraylist<string> (); for (int i:num) {Numstr.add ("" + i);} Collections.sort (Numstr, New Stringcomparator ()); <span style= "White-space:pre" ></span>//Trim the leading zero (s). Boolean HASPOSSIBLELEADING0 = True;for ( int i = Numstr.size ()-1; I >= 0; -i) {if (HasPossibleLeading0 && numstr.get (i). Equals ("0")) continue; HASPOSSIBLELEADING0 = False;sb.append (Numstr.get (i));} if (sb.length () = = 0) {return "0";} return sb.tostring (); }
[Leetcode] Largest number