面试题45. 把数组排成最小的数
可以使用Arrays.sort()进行排序,也可以自己写一个排序算法,面试时建议自己写排序算法
class Solution {
public String minNumber(int[] nums) {
String[] strs = new String[nums.length];
for(int i = 0; i < nums.length; i++) {
strs[i] = String.valueOf(nums[i]);
}
quickSort(strs, 0, strs.length - 1);
//Arrays.sort(strs, (x, y) -> (x + y).compareTo(y + x));
StringBuilder res = new StringBuilder();
for(String s : strs) {
res.append(s);
}
return res.toString();
}
public void quickSort(String[] strs, int l, int r) {
if(l > r) return;
int i = l;
int j = r;
String temp = strs[i];
while(i < j) {
//找小于l的数
while((strs[j] + strs[l]).compareTo(strs[l] + strs[j]) >= 0 && i < j) j--;//j大于l
//找大于l的数
while((strs[i] + strs[l]).compareTo(strs[l] + strs[i]) <= 0 && i < j) i++;//i小于l
//交换
temp = strs[i];
strs[i] = strs[j];
strs[j] = temp;
}
strs[i] = strs[l];
strs[l] = temp;
quickSort(strs, l, i - 1);
quickSort(strs, i + 1, r);
}
}