largest number
Given a list of non negative integers, arrange them such that they form the largest number.
For example, given [3, 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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Solution 1:
The solution of reference http://bookshadow.com/weblog/2015/01/13/leetcode-largest-number/:
Greedy idea: For two alternative numbers a and B, if Str (a) + str (b) > str (b) + str (a), then a before B, otherwise b before a
Follow this principle to sort the original array from large to small
Time complexity O (NLOGN)
Error-prone Example:
Input: [0,0]
Output: "00"
Expected: "0"
JAVA CODE:
1 Public classSolution {2 PublicString Largestnumber (int[] num) {3 //10454 //1111 begin.5 if(num = =NULL) {6 return NULL;7 }8 9arraylist<integer> list =NewArraylist<integer>();Ten for(intn1:num) { One List.add (N1); A } - -Collections.sort (list,NewComparator<integer>(){ the Public intCompare (integer O1, integer o2) { -String S1 =""+ O1 +O2; -String s2 =""+ O2 +O1; - + returnS2.compareto (S1); - } + }); A atStringBuilder SB =NewStringBuilder (); - for(intn:list) { - sb.append (n); - } - - if(Sb.charat (0) =='0') { in return "0"; - } to + returnsb.tostring (); - } the}
View Code
Attach some explanations about comparator, comparable:
Comparator is an independent comparator, inside implements "compare", and comparable can be implement by class itself.
Http://stackoverflow.com/questions/4108604/java-comparable-vs-comparator
Java:comparable vs Comparator [duplicate]
When your class implements comparable, the CompareTo method of the class was defining the "natural" ordering of that object . That method was contractually obligated (though not demanded) to being in line with other methods on that object, such as a 0 Should always is returned for objects when the. Equals () comparisons return true.
A Comparator is it own definition of how-to compare-objects, and can be used-compare objects in a-a-to-might n OT align with the natural ordering.
For example, Strings is generally compared alphabetically. Thus the "a". CompareTo ("B") would use alphabetical comparisons. If you wanted to compare Strings on length, you would need to write a custom comparator.
In short, there isn ' t much difference. They is both ends to similar means. In general implement comparable for natural order, (natural order definition was obviously open to interpretation), and WRI Te a comparator for other sorting or comparison needs.
Related reference:
http://examples.javacodegeeks.com/core-java/util/comparator/java-comparator-example/
Leetcode:largest Number Problem Solving report