【題目】
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();
}