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 is9534330
.
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.
思路:要想比较两个数在最终结果中的先后位置,何不直接比较一下不同组合的结果大小?
举个例子:要比较3和34的先后位置,可以比较334和343的大小,而343比334大,所以34应当在前。
就是我们把两个数拼在一起,然后再把这两个数换个顺序再拼在一起,这时候就可以直接比较了。比如2332和23,变成233223和232332两个数,这时候那个数更大,就说明这个数前半部分的那个数是更大的,这里是2332。
如果排序后第一个数是0,则直接返回0,因为后面的数只有可能是0了.
class Solution {
public String largestNumber(int[] nums) {
if(nums == null || nums.length == 0) {
return null;
}
Integer[] copyNums = new Integer[nums.length];
for(int i = 0; i < nums.length; i++) {
copyNums[i] = nums[i];
}
StringBuilder sb = new StringBuilder();
Arrays.sort(copyNums, new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
String as = String.valueOf(a);
String bs = String.valueOf(b);
return (bs + as).compareTo(as + bs);
}
});
if(copyNums[0] == 0) {
return "0";
}
for(int i = 0; i < copyNums.length; i++) {
sb.append(copyNums[i]);
}
return sb.toString();
}
}