Given a list of non negative integers, arrange them such that they form the largest number.
Example 1:
Input: [10,2]
Output: "210"
Example 2:
Input: [3,30,34,5,9]
Output: "9534330"
Note: The result may be very large, so you need to return a string instead of an integer.
0. 为了构建最大数字,我们希望越高位的数字越大越好。
1.传递性。
2.比较a~b 还是 b~a 大时, 可以用两种不同的排列来对比。这样更简单。开始居然想用一位位的取比较。 直接把自己绕进去。
3.然后先用升序排出来, 再按降序组装, 这样 更容易看懂。
4.注意, 【“0”,“0”】的情况 应该是只要返回“0”
1 public String largestNumber(int[] nums) { 2 Comparator cmp = new MyComparator(); 3 String[] strings = new String[nums.length]; 4 for (int i = 0; i < strings.length; i++) { 5 strings[i] = String.valueOf(nums[i]); 6 } 7 // ascending order 8 Arrays.sort(strings, cmp); 9 StringBuilder sb = new StringBuilder(); 10 // if ["0","0"],only return one "0"; 11 if(strings[strings.length-1].equals("0")){ 12 return "0"; 13 } 14 for (int i = strings.length - 1; i >= 0; i--) { 15 sb.append(strings[i]); 16 } 17 return sb.toString(); 18 } 19 //ascending order of the nums. 20 21 class MyComparator implements Comparator<String> { 22 @Override 23 public int compare(String o1, String o2) { 24 String s1 = o1 + o2; 25 String s2 = o2 + o1; 26 return s1.compareTo(s2); 27 } 28 }
reference : https://leetcode-cn.com/problems/largest-number/solution/zui-da-shu-by-leetcode/
原文:https://www.cnblogs.com/tangdatou/p/12404132.html