Skip to content

Commit 00d02f2

Browse files
committed
feat: top-k-frequent-elements
1 parent f9b368d commit 00d02f2

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// https://leetcode.com/problems/top-k-frequent-elements/
2+
3+
// TC: O(nlogn)
4+
// SC: O(n)
5+
6+
function topKFrequent(nums: number[], k: number): number[] {
7+
const map = new Map()
8+
9+
for (const num of nums) {
10+
if (map.has(num)){
11+
map.set(num, map.get(num) + 1)
12+
} else {
13+
map.set(num, 1)
14+
}
15+
}
16+
17+
const sortedMap = [...map].sort((a, b)=> b[1]- a[1])
18+
return sortedMap.splice(0, k).map((item)=> item[0])
19+
};

0 commit comments

Comments
 (0)