Skip to content

Commit a174898

Browse files
committed
3: top k frequent elements
1 parent ca6916c commit a174898

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
function topKFrequent(nums: number[], k: number): number[] {
2+
const dict: Map<number, number> = new Map();
3+
4+
// TC: O(N)
5+
// SC: O(N)
6+
nums.forEach((n) => {
7+
if (!dict.has(n)) dict.set(n, 1);
8+
else {
9+
dict.set(n, dict.get(n) + 1);
10+
}
11+
});
12+
13+
// TC: O(N)
14+
// SC: O(N)
15+
const buckets: number[][] = Array(nums.length + 1)
16+
.fill(0)
17+
.map((_) => []);
18+
Array.from(dict.entries()).forEach(([num, cnt]) => {
19+
buckets[cnt].push(num);
20+
});
21+
22+
// TC: O(N) + O(k) = O(N)
23+
// SC: O(N)
24+
return buckets.flat().slice(-k);
25+
}
26+
27+
// TC: O(N)
28+
// SC: O(N)

0 commit comments

Comments
 (0)