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 48 49 50 51 52 53 54 55 56 57 58
| class TopK { public static int[] getTopK(int[] arr, int k) { if (k == 0) return new int[0]; else if (k >= arr.length) return arr; int low = 0; int high = arr.length -1; partitionArray(arr, low, high, k); int[] result = new int[k]; for (int copy = 0; copy < k; copy++){ result[copy] = arr[copy]; } return result; }
private static void partitionArray(int[] arr, int low, int high, int k) { int m = partition(arr, low, high); if (k == m) return; else if (k < m) partitionArray(arr, low, m -1, k); else partitionArray(arr, m + 1, high, k); }
private static int partition(int[] arr, int low, int high){ int i = low; int j = high + 1; int v = arr[low];
while (true) { while (arr[++i] < v) { if (i == high) { break; } } while (arr[--j] > v) { if (j == low) { break; } }
if (i >= j) { break; } swap(arr, i, j); } swap(arr, low, j); return j; }
private static void swap(int[]arr, int i, int j){ int t = arr[i]; arr[i] = arr[j]; arr[j] = t; }
|