Construct minimum number by reordering a given non-negative integer array. Arrange them such that they form the minimum number.
Notice
The result may be very large, so you need to return a string instead of an integer.
Have you met this question in a real interview?
Example
Given [3, 32, 321]
, there are 6 possible numbers can be constructed by reordering the array:
3+32+321=332321
3+321+32=332132
32+3+321=323321
32+321+3=323213
321+3+32=321332
321+32+3=321323
So after reordering, the minimum number is 321323
, and return it.
分析:
这里需要对数组进行排序,那么怎么比较大小呢?对于数A和B,如果AB在一起组成的数小于BA组成的数,我们就认为A<B,反之亦然。
public static String minNumber(int[] nums) {
if (nums == null || nums.length == )
return ""; String[] strs = new String[nums.length];
for (int i = ; i < nums.length; i++) {
strs[i] = String.valueOf(nums[i]);
} Arrays.sort(strs, new Comparator<String>() {
public int compare(String str1, String str2) {
return (str1 + str2).compareTo(str2 + str1);
}
}); StringBuilder sb = new StringBuilder();
for (String str : strs) {
sb.append(str);
}
for (int i = ; i < sb.length(); i++) {
if (sb.charAt(i) != '') {
return sb.substring(i);
}
}
return "";
}