Largest Number
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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
思路:
对数组进行排序,排序规则:如[3,34],它们的组合有334和343。明显334小于343,因此3排序在34前面。
java code:
public class Solution {
public String largestNumber(int[] nums) {
if(nums == null || nums.length == 0) return "0";
StringBuffer sb = new StringBuffer();
String[] tmps = new String[nums.length];
for(int i = 0; i< nums.length; i++) {
tmps[i] = nums[i] + "";
}
Comparator<String> cmp = new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
String str1 = o1 + o2;
String str2 = o2 + o1;
return str2.compareTo(str1);
}
};
Arrays.sort(tmps, cmp);
if(tmps[0].charAt(0)=='0') return "0"; // 处理[0,0]这种情况
for(String str : tmps) {
sb.append(str);
}
return sb.toString();
}
}