Skip to content

Commit b776697

Browse files
committed
Top K Frequent Elements
1 parent 0ada062 commit b776697

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

top-k-frequent-elements/hyejjun.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} k
4+
* @return {number[]}
5+
*/
6+
var topKFrequent = function (nums, k) {
7+
const count = {};
8+
9+
nums.forEach((num) => {
10+
count[num] = (count[num] || 0) + 1;
11+
});
12+
13+
const filtered = Object.keys(count).sort((a, b) => count[b] - count[a]);
14+
15+
return filtered.slice(0, k).map(Number);
16+
17+
};
18+
19+
console.log(topKFrequent([1, 1, 1, 2, 2, 3], 2)); // [1, 2]
20+
console.log(topKFrequent([1], 1)); // [1]
21+
22+
/*
23+
Time Complexity : O(NLogN)
24+
Space Complexity: O(N)
25+
*/

0 commit comments

Comments
 (0)