|
| 1 | +package quickselect; |
| 2 | + |
| 3 | +import lib.Printer; |
| 4 | + |
| 5 | +import java.util.HashMap; |
| 6 | +import java.util.Map; |
| 7 | +import java.util.Random; |
| 8 | + |
| 9 | +public class Problem347_TopKFrequentElements { |
| 10 | + |
| 11 | + Map<Integer, Integer> map; |
| 12 | + |
| 13 | + public int[] topKFrequent(int[] A, int k) { |
| 14 | + map = new HashMap<>(); |
| 15 | + for (int a : A) map.put(a, map.getOrDefault(a, 0)+1); |
| 16 | + |
| 17 | + int i = 0, n = map.size(), nums[] = new int[n]; |
| 18 | + for (int a : map.keySet()) nums[i++] = a; |
| 19 | + |
| 20 | + findKthLargest(nums, k); |
| 21 | + |
| 22 | + int[] res = new int[k]; |
| 23 | + for (i = n-k; i < n; i++) { |
| 24 | + res[i-n+k] = nums[i]; |
| 25 | + } |
| 26 | + return res; |
| 27 | + } |
| 28 | + |
| 29 | + public void swap(int[] A, int i, int j) { |
| 30 | + if (i == j) return; |
| 31 | + int tmp = A[i]; |
| 32 | + A[i] = A[j]; |
| 33 | + A[j] = tmp; |
| 34 | + } |
| 35 | + |
| 36 | + public void shuffle(int[] A) { |
| 37 | + Random random = new Random(); |
| 38 | + // Attention: Reverse loop |
| 39 | + for (int i = A.length-1; i >= 0; i--) { |
| 40 | + swap(A, i, random.nextInt(i+1)); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + public int findKthLargest(int[] A, int k) { |
| 45 | + int lo = 0, hi = A.length-1; k = A.length-k; |
| 46 | + // without suffle: O(N) best case / O(N^2) worst case running time + O(1) memory |
| 47 | + // with suffle: the probability O(N) is rare (1/N!), O(1) memory |
| 48 | + shuffle(A); |
| 49 | + while (true) { |
| 50 | + int pivot = quickselect(A, lo, hi); |
| 51 | + if (pivot == k) break; |
| 52 | + if (pivot < k) lo = pivot+1; |
| 53 | + else hi = pivot-1; |
| 54 | + } |
| 55 | + return A[k]; |
| 56 | + } |
| 57 | + |
| 58 | + public int quickselect(int[] A, int lo, int hi) { |
| 59 | + int pivot = lo; // choose the pivot at lo |
| 60 | + while (true) { |
| 61 | + while (lo <= hi && map.get(A[lo]) <= map.get(A[pivot])) lo++; |
| 62 | + while (lo <= hi && map.get(A[hi]) > map.get(A[pivot])) hi--; |
| 63 | + if (lo > hi) break; |
| 64 | + swap(A, lo, hi); |
| 65 | + } |
| 66 | + swap(A, hi, pivot); |
| 67 | + return hi; |
| 68 | + } |
| 69 | + |
| 70 | + public static void run() { |
| 71 | + Problem347_TopKFrequentElements solution = new Problem347_TopKFrequentElements(); |
| 72 | + int k = 2, A[] = {1,1,1,2,2,3}; |
| 73 | + int[] res = solution.topKFrequent(A, k); |
| 74 | + Printer.print(res); |
| 75 | + } |
| 76 | +} |
0 commit comments