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,30,34,5,9] -> [9,5,3,43,30] ->[9534330]
将数组里的每一个String排序,然后按照从大到小的顺序从StringBuffer里
public String largestNumber(int[] nums) {
String[] arr=new String[nums.length];
for(int i=0;i<nums.length;i++){
arr[i]=nums[i]+"";
}
Arrays.sort(arr,new Comparator<String>(){
public int compare(String i,String j){
String s1 = i+j;
String s2 = j+i;
return s1.compareTo(s2);
}
});
if(arr[arr.length-1].charAt(0)=='0'){
return "0";
}
StringBuffer sb=new StringBuffer();
for(int i=arr.length-1;i>=0;i--){
sb.append(arr[i]);
}
return sb.toString();
}