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.
解题思路:
该题目需要防止出现都是0的状态
java
class Solution {
public String largestNumber(int[] nums) {
if (nums == null || nums.length == 0) {
return "";
}
Integer[] arr = new Integer[nums.length];
for (int i = 0; i < nums.length; i++) {
arr[i] = new Integer(nums[i]);
}
Comparator<Integer> cmp = new Comparator<Integer>() {
public int compare(Integer a1, Integer a2) {
String str1 = a1 + "" + a2;
String str2 = a2 + "" + a1;
return -str1.compareTo(str2);
}
};
Arrays.sort(arr, cmp);
StringBuffer sb = new StringBuffer();
for (int val : arr) {
sb.append(val);
}
String str = sb.toString();
if (str.charAt(0) == '0' && str.charAt(str.length() - 1) == '0') {
return 0 + "";
} else {
return str;
}
}
}