classSolution{ public String minNumber(int[] nums){ int[] number = nums; if (number == null || number.length == 0) { returnnew String(); } String[] strNumber = new String[number.length]; for (int i=0; i<number.length; i++) { strNumber[i] = String.valueOf(number[i]); } // 快排 quickSort(strNumber, 0, strNumber.length-1); // 结果转换 StringBuilder res = new StringBuilder(); for (String str : strNumber) { res.append(str); } return res.toString(); }
voidquickSort(String[] strNumber, int start, int end){ if (start >= end ) return; int index = partition(strNumber, start, end); if (index > start) { quickSort(strNumber, start, index-1); } if (index < end) { quickSort(strNumber, index+1, end); } }
intpartition(String[] strNumber, int start, int end){
int left = start; int right = end; String temp = strNumber[left]; while (left < right) { while (left < right && ((strNumber[right]+strNumber[left]).compareTo(strNumber[left]+strNumber[right]))>=0) { right--; } while (left < right && ((strNumber[left]+strNumber[right]).compareTo(strNumber[right]+strNumber[left]) <= 0)) { left++; } temp = strNumber[left]; strNumber[left] = strNumber[right]; strNumber[right] = temp; } strNumber[left] = temp; return left;
} }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// 方法二 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]); } // 快排 Arrays.sort(strs, (x, y)->(x+y).compareTo(y+x)); StringBuilder res = new StringBuilder(); for(String str : strs) { res.append(str); } return res.toString(); }