|
| 1 | +// Approach 2: Min-Heap |
| 2 | +// ⏳ Time Complexity: O(n log(k)) |
| 3 | +// 💾 Space Complexity: O(n) |
| 4 | + |
| 5 | +function topKFrequent(nums: number[], k: number): number[] { |
| 6 | + const map = new Map<number, number>(); |
| 7 | + // step 1: count frequency of each number |
| 8 | + for (const num of nums) { |
| 9 | + map.set(num, (map.get(num) || 0) + 1); |
| 10 | + } |
| 11 | + |
| 12 | + // step 2: use a min-heap to keep only top k frequent elements |
| 13 | + // A Min-Heap is a special type of binary heap (tree-based data structure) where: |
| 14 | + // The smallest element is always at the root (top). |
| 15 | + |
| 16 | + const minHeap: [number, number][] = []; |
| 17 | + |
| 18 | + // Time Complexity: O(n log k) |
| 19 | + // Sorting is within a fixed size k which is much smaller than O(n log n) sorting all elements. |
| 20 | + for (const [num, freq] of map.entries()) { |
| 21 | + if (minHeap.length < k) { |
| 22 | + minHeap.push([num, freq]); |
| 23 | + minHeap.sort((a, b) => a[1] - b[1]); |
| 24 | + } else if (freq > minHeap[0][1]) { |
| 25 | + minHeap.shift(); // Remove smallest frequency |
| 26 | + minHeap.push([num, freq]); |
| 27 | + minHeap.sort((a, b) => a[1] - b[1]); |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + // step 3: extract the top k freqeuent elements from the heap |
| 32 | + return minHeap.map(([num, freq]) => num); |
| 33 | +} |
| 34 | + |
| 35 | + |
| 36 | +// Approach 1: Map & Sorting (Using Map in TypeScript) |
| 37 | +// ⏳ Time Complexity: O(n log(n)) |
| 38 | +// 💾 Space Complexity: O(n) |
| 39 | +// function topKFrequent(nums: number[], k: number): number[] { |
| 40 | + |
| 41 | +// const map = new Map<number, number>() |
| 42 | + |
| 43 | +// for (const num of nums) { |
| 44 | +// map.set(num, (map.get(num) || 0) + 1); |
| 45 | +// } |
| 46 | + |
| 47 | +// // const sorted = [...map.entries()].sort((a, b) => b[1] - a[1]); |
| 48 | +// const sorted = Array.from(map).sort((a, b) => b[1] - a[1]); |
| 49 | + |
| 50 | +// return sorted.slice(0, k).map(item => item[0]); |
| 51 | +// }; |
| 52 | + |
0 commit comments