Leetcode: Largest Number
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.
聪明方法:其实干嘛要挨个比呢,按最直接的方法,接起来,谁大谁在前:
可以换一下思路,要想比较两个数在最终结果中的先后位置,何不直接比较一下不同组合的结果大小?
举个例子:要比较3和34的先后位置,可以比较334和343的大小,而343比334大,所以34应当在前。
这样,有了比较两个数的方法,就可以对整个数组进行排序。然后再把排好序的数拼接在一起就好了。
首先把int 全部转换成string array,然后,自己写一个comparator,判断ab ba的大小,从而把a,b排序
然后把所有的连起来,记住,大的在后面,从后面开始连接。最后去掉前面的0;
1 public class Solution { 2 public String largestNumber(int[] num) { 3 if(num == null || num.length == 0) 4 return ""; 5 6 // Convert int array to String array, so we can sort later on 7 String[] s_num = new String[num.length]; 8 for(int i = 0; i < num.length; i++) 9 s_num[i] = String.valueOf(num[i]); 10 11 // Comparator to decide which string should come first in concatenation 12 Comparator<String> comp = new Comparator<String>(){ 13 @Override 14 public int compare(String str1, String str2){ 15 String s1 = str1 + str2; 16 String s2 = str2 + str1; 17 return s2.compareTo(s1); // reverse order here, so we can do append() later 18 } 19 }; 20 21 Arrays.sort(s_num, comp); 22 // An extreme edge case by lc, say you have only a bunch of 0 in your int array 23 if(s_num[0].charAt(0) == '0') 24 return "0"; 25 26 StringBuilder sb = new StringBuilder(); 27 for(String s: s_num) 28 sb.append(s); 29 30 return sb.toString(); 31 32 } 33 }