lc179 Largest Number
The main test comparator rewrite, the idea is very simple
The int [] turn into String [], and then descending row
The results can then turn into the string lined up
How to sort? According to what rules?
Look at a few examples
"9" "987" -> "9987" > "9879"
"123" "213" -> "123213" < "213123"
This shows that we need only compare s1 + s2? S2 + s1 to
It should be rewritten to use comparator
. 1 Comparator <String> COM = new new Comparator <String> () { 2 // @Override . 3 public int Compare (String S1, S2 String) { // Note that the return value int, the return value == 0, s1 == S2;> 0, S1> S2; <0, S2 <S1 . 4 String TMP1 = S1 + S2; . 5 String TMP2 = S2 + S1; . 6 return tmp2.compareTo (TMP1); // the compareTo () returns the value is int, supra rules ; but since compare is ranked by ascending order of default, that is> 0 element rows behind, so here we use tmp2.compareTo () . 7 } . 8 };
There is a corner case, if the original int [] is a bunch of [0, 0, 0, 0], will return to "0000", so we have to consider the case
1 class Solution { 2 public String largestNumber(int[] nums) { 3 if(nums == null || nums.length == 0){ 4 return ""; 5 } 6 7 String[] res = new String[nums.length]; 8 9 for(int i=0; i<nums.length; i++){ 10 res[i] = String.valueOf(nums[i]); 11 } 12 13 Comparator<String> com = new Comparator<String>(){ 14 //@Override 15 public int compare(String s1, String s2){ 16 String tmp1 = s1+s2; 17 String tmp2 = s2+s1; 18 return tmp2.compareTo(tmp1); 19 } 20 }; 21 22 Arrays.sort(res, com); 23 if(res[0].charAt(0) == '0') 24 return "0"; 25 26 StringBuilder sb = new StringBuilder(); 27 for(String i :res) 28 sb.append(i); 29 30 return sb.toString(); 31 } 32 }