Skip to content

Commit f3326a8

Browse files
committed
top-k-frequent-elements
1 parent b31642f commit f3326a8

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* 347. Top K Frequent Elements
3+
* Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in
4+
* any order.
5+
* https://leetcode.com/problems/top-k-frequent-elements/description/
6+
*/
7+
function topKFrequent(nums: number[], k: number): number[] {
8+
const map = new Map<number, number>();
9+
10+
nums.forEach((n) => {
11+
const count = map.get(n);
12+
if (count) {
13+
map.set(n, count + 1);
14+
return;
15+
}
16+
map.set(n, 1);
17+
});
18+
19+
const kvArray = [...map];
20+
const sorted = kvArray.sort(([, v1], [, v2]) => v2 - v1);
21+
22+
const result: number[] = [];
23+
for (let i = 0; i < k; i++) {
24+
result.push(sorted[i][0]);
25+
}
26+
27+
return result;
28+
}
29+
30+
// O(n) time
31+
// O(n) space

0 commit comments

Comments
 (0)