Skip to content

Commit 7b15045

Browse files
committed
Top K Frequent Elements Solution
1 parent df1514a commit 7b15045

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

top-k-frequent-elements/naringst.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} k
4+
* @return {number[]}
5+
*/
6+
7+
/**
8+
* Runtime: 64ms, Memory: 53.31MB
9+
*
10+
* Time complexity: O(NlogN)
11+
* - frquentEntries.sort: NlogN
12+
* Space complexity: O(n)
13+
*
14+
* **/
15+
16+
var topKFrequent = function (nums, k) {
17+
let answer = [];
18+
19+
const frequent = {};
20+
for (const num of nums) {
21+
frequent[num] = frequent[num] ? frequent[num] + 1 : 1;
22+
}
23+
24+
const frequentEntries = Object.entries(frequent);
25+
frequentEntries.sort((a, b) => b[1] - a[1]);
26+
27+
const topK = frequentEntries.slice(0, k).map((i) => i[0]);
28+
29+
return topK;
30+
};

0 commit comments

Comments
 (0)