【题目】
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来进行比较,因为呢,变成字符的话呢,他就会按照字符的顺序来进行排序了。
注意,要做一个comparator.
【代码】
public String largestNumber(int[] num) {
if(num==null || num.length==0)
return "";
String[] Snum = new String[num.length];
for(int i=0;i<num.length;i++)
Snum[i] = num[i]+"";
Comparator<String> comp = new Comparator<String>(){
@Override
public int compare(String str1, String str2){ //比较两个组合起来,哪一个组合更大。
String s1 = str1+str2; //比如:12,121 -:12121,12112
String s2 = str2+str1;
return s1.compareTo(s2);
}
};
//查看最后一个字符是不是为0 ,如果为0,就说明最大的就是0 ,那么整体就是0 。
Arrays.sort(Snum,comp);
if(Snum[Snum.length-1].charAt(0)=='0')
return "0";
StringBuilder sb = new StringBuilder();
for(String s: Snum)
sb.insert(0, s);
return sb.toString();
}