lc179 Largest Number
主要考comparator的重写,思路很简单
将int[]转成String[],然后排降序
排好之后依次放入结果字符串即可
如何排序?按什么规则呢?
先看几个例子
"9" "987" -> "9987" > "9879"
"123" "213" -> "123213" < "213123"
可见我们只需要比较s1+s2 ? s2+s1即可
这里需要用到comparator重写
1 Comparator<String> com = new Comparator<String>(){ 2 //@Override 3 public int compare(String s1, String s2){//注意这里返回值为int,返回值==0,s1==s2; >0,s1>s2; <0, s2<s1 4 String tmp1 = s1+s2; 5 String tmp2 = s2+s1; 6 return tmp2.compareTo(tmp1);//compareTo()返回值也是int,规则同上; 但是由于compare默认是按照升序排的,就是说>0的元素排后面,所以这里我们用tmp2.compareTo() 7 } 8 };
还有一个corner case,若原int[]就是一堆[0, 0, 0, 0],会返回"0000",所以我们要考虑这种情况
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 }