179 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;
public class Solution { public String largestNumber(int[] num) { if(num == null || num.length == 0) return ""; // Convert int array to String array, so we can sort later on String[] s_num = new String[num.length]; for(int i = 0; i < num.length; i++) s_num[i] = String.valueOf(num[i]); // Comparator to decide which string should come first in concatenation Comparator<String> comp = new Comparator<String>(){ @Override public int compare(String str1, String str2){ String s1 = str1 + str2; String s2 = str2 + str1; return s2.compareTo(s1); // reverse order here, so we can do append() later } }; Arrays.sort(s_num, comp); // An extreme edge case by lc, say you have only a bunch of 0 in your int array if(s_num[0].charAt(0) == '0') return "0"; StringBuilder sb = new StringBuilder(); for(String s: s_num) sb.append(s); return sb.toString(); } }
奇技淫巧:
Comparator<String> comp = new Comparator<String>(){ @Override public int compare(String str1, String str2){ String s1 = str1 + str2; String s2 = str2 + str1; return s2.compareTo(s1); // reverse order here, so we can do append() later } };