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 be very large, so you need to return a string instead of an integer.
含义:给定多个非负数,将他们排列成一个最大数,用string返回
1 public String largestNumber(int[] nums) { 2 if(nums == null || nums.length == 0) 3 return ""; 4 5 // Convert int array to String array, so we can sort later on 6 String[] s_num = new String[nums.length]; 7 for(int i = 0; i < nums.length; i++) 8 s_num[i] = String.valueOf(nums[i]); 9 10 // Comparator to decide which string should come first in concatenation 11 Comparator<String> comp = new Comparator<String>(){ 12 @Override 13 public int compare(String str1, String str2){ 14 String s1 = str1 + str2; 15 String s2 = str2 + str1; 16 return s2.compareTo(s1); // reverse order here, so we can do append() later 17 } 18 }; 19 20 Arrays.sort(s_num, comp);//由顶到底,前一个元素加后一个元素的值,大于后一个元素加前一个元素的值 21 // An extreme edge case by lc, say you have only a bunch of 0 in your int array 22 if(s_num[0].charAt(0) == '0') 23 return "0"; 24 25 StringBuilder sb = new StringBuilder(); 26 for(String s: s_num) 27 sb.append(s); 28 29 return sb.toString(); 30 }