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.
算法: Collections.sort(List<T> list,Comparator<T> c)
当a+b >b+a 时, a一定出现在b的前面,证明:
1. 显然abc>bac,cab>cba
2. a>c>b: acb和bca不可能同时出现
public class Solution {
public String largestNumber(int[] nums) {
//abc>cbabu hui chuxian
ArrayList<Token> tokens=new ArrayList<Token>();
for(int i:nums)
{
tokens.add(new Token(i));
}
Collections.sort(tokens, new Comparator<Token>()
{
public int compare(Token a, Token b)
{
String s1=new String(a.s+b.s), s2=new String(b.s+a.s);
for(int i=0;i<s1.length();i++)
{
if(s1.charAt(i)<s2.charAt(i))return 1;
else if(s1.charAt(i)>s2.charAt(i))return -1;
}
return 0;
}
});
StringBuffer sb=new StringBuffer();
for(int i=0;i<tokens.size();i++)
{
sb.append(tokens.get(i).s);
}
while(sb.length()>0 && sb.charAt(0)=='0')sb.deleteCharAt(0);
if(sb.length()==0)return "0";
return sb.toString();
}
}
class Token
{
String s;
Token(int x)
{
s=String.valueOf(x);
}
}