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.
思路:首先将起转换为字符串,因为这涉及到比较每一位的大小,先排序,判断2个字符串大小主要依据是(s1+s2)与(s2+s1)的大小。
public class Solution {
public String largestNumber(int[] nums) {
int n=nums.length;
String[] str=new String[n];
for(int i=0;i<n;i++){
str[i]=""+nums[i];
}
Arrays.sort(str,new Comparator<String>(){
public int compare(String s1,String s2){
String c1=s1+s2;
String c2=s2+s1;
return c1.compareTo(c2);
}
});
String ans="";
for(int i=0;i<n;i++)
ans=str[i]+ans;
if(ans.charAt(0)=='0')
return "0";
return ans;
}
}