|
| 1 | +import java.util.*; |
| 2 | + |
| 3 | +// link: https://leetcode.com/problems/top-k-frequent-elements/description/ |
| 4 | +// difficulty: Medium |
| 5 | + |
| 6 | +// Time complexity: O(Nlogk) |
| 7 | +// Space complexity: O(N) |
| 8 | +class Solution1 { |
| 9 | + // return: top k most freq elements |
| 10 | + public int[] topKFrequent(int[] nums, int k) { |
| 11 | + HashMap<Integer, Integer> freq = new HashMap<>(); |
| 12 | + // O (N) |
| 13 | + for(int num : nums) { |
| 14 | + freq.put(num, freq.getOrDefault(num, 0) + 1); // O(1) |
| 15 | + } |
| 16 | + |
| 17 | + // O (N log k) |
| 18 | + PriorityQueue<int[]> heap = new PriorityQueue<>(Comparator.comparingInt(a -> a[1])); |
| 19 | + for(int num : freq.keySet()) { |
| 20 | + int f = freq.get(num); // O(1) |
| 21 | + heap.add(new int[]{num, f}); // O(log k) |
| 22 | + |
| 23 | + if(heap.size() > k) heap.poll(); // O(log k) |
| 24 | + } |
| 25 | + |
| 26 | + // O (N log k) |
| 27 | + int[] result = new int[k]; |
| 28 | + for(int i = 0; i < k; i++) { |
| 29 | + result[i] = heap.poll()[0]; // O(log k) |
| 30 | + } |
| 31 | + |
| 32 | + return result; |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +// Time complexity: O(N) |
| 37 | +// Space complexity: O(N) |
| 38 | +class Solution2 { |
| 39 | + public int[] topKFrequent(int[] nums, int k) { |
| 40 | + // count frequencies |
| 41 | + Map<Integer, Integer> freq = new HashMap<>(); |
| 42 | + for (int num : nums) { |
| 43 | + freq.put(num, freq.getOrDefault(num, 0) + 1); |
| 44 | + } |
| 45 | + |
| 46 | + // bucket: index = frequency, value = list of numbers |
| 47 | + List<List<Integer>> buckets = new ArrayList<>(nums.length + 1); |
| 48 | + for (int i = 0; i <= nums.length; i++) { |
| 49 | + buckets.add(new ArrayList<>()); |
| 50 | + } |
| 51 | + |
| 52 | + for (var entry : freq.entrySet()) { |
| 53 | + int num = entry.getKey(); |
| 54 | + int count = entry.getValue(); |
| 55 | + buckets.get(count).add(num); |
| 56 | + } |
| 57 | + |
| 58 | + // gather top k frequent elements |
| 59 | + int[] result = new int[k]; |
| 60 | + int idx = 0; |
| 61 | + for (int i = nums.length; i >= 0 && idx < k; i--) { |
| 62 | + for (int num : buckets.get(i)) { |
| 63 | + result[idx++] = num; |
| 64 | + if (idx == k) break; |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + return result; |
| 69 | + } |
| 70 | +} |
0 commit comments