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
| class Solution { public int[] getLeastNumbers(int[] arr, int k) { if (k == 0) { return new int[0]; }
int targetIndex = k - 1; quickSort(arr, 0, arr.length - 1, targetIndex); return Arrays.copyOf(arr, k); }
private void quickSort(int[] arr, int i, int j, int targetIndex) { if (i >= j) { return; }
int pivotIndex = partition(arr, i, j); if (pivotIndex == targetIndex) { return; } quickSort(arr, i, pivotIndex - 1, targetIndex); quickSort(arr, pivotIndex + 1, j, targetIndex); }
private int partition(int[] arr, int i, int j) { int pivotIndex = i + ThreadLocalRandom.current().nextInt(j - i + 1); int pivotValue = arr[pivotIndex]; swap(arr, pivotIndex, i);
int index = i; for (int k = i + 1; k <= j; k++) { if (arr[k] <= pivotValue) { swap(arr, k, ++index); } }
swap(arr, i, index); return index; }
private void swap(int[] nums, int i, int j) { int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; } }
|