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
.
本题不能用全排列,否则超时,研究此题,便知此题是考察字符串的排序,代码如下
public class Solution {
public String largestNumber(int[] nums) {
if(nums == null || nums.length == 0){
return "0";
}
String[] numsStrArr = new String[nums.length];
for(int i = 0; i < nums.length; i++){
numsStrArr[i] = ""+nums[i];
}
Arrays.sort(numsStrArr, new Comparator<String>(){
public int compare(String a, String b){
String l2r = a + b;
String r2l = b + a;
return -l2r.compareTo(r2l);
}
});
StringBuilder sb = new StringBuilder();
for(String s : numsStrArr){
sb.append(s);
}
while(sb.charAt(0) == '0' && sb.length() > 1){
sb.deleteCharAt(0);
}
return sb.toString();
}
}