1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| class Solution { public String minNumber(int[] nums) { List<String> numList = new ArrayList<>(nums.length); for (int num : nums) { numList.add(String.valueOf(num)); }
quickSort(numList, 0, numList.size() - 1);
return String.join("", numList); }
private void quickSort(List<String> numList, int i, int j) { if (i >= j) { return; }
int pivotIndex = partition(numList, i, j); quickSort(numList, i, pivotIndex - 1); quickSort(numList, pivotIndex + 1, j); }
private int partition(List<String> numList, int i, int j) { int pivotIndex = i + ThreadLocalRandom.current().nextInt(j - i + 1); String pivotValue = numList.get(pivotIndex); swap(numList, pivotIndex, i); int index = i; for (int k = i + 1; k <= j; k++) { if (lessThan(numList.get(k), pivotValue)) { swap(numList, k, ++index); } }
swap(numList, index, i); return index; }
private boolean lessThan(String a, String b) { return (a + b).compareTo(b + a) < 0; }
private void swap(List<String> numList, int i, int j) { String tmp = numList.get(i); numList.set(i, numList.get(j)); numList.set(j, tmp); } }
|