Skip to content

Commit e56eacb

Browse files
committed
Top K Frequent Elements
1 parent cafa20c commit e56eacb

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

top-k-frequent-elements/sunjae95.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* @description
3+
* time complexity: O(N logN)
4+
* space complexity: O(N)
5+
*
6+
* brainstorming:
7+
* 1. javascript sort method
8+
* 2. priority queue
9+
*
10+
* strategy:
11+
* javascript sort method
12+
*
13+
* reason:
14+
* javascript sort method is easier to implement.
15+
*/
16+
17+
var topKFrequent = function (nums, k) {
18+
const answer = [];
19+
const array = [];
20+
const hashTable = new Map();
21+
22+
nums.forEach((num) => hashTable.set(num, (hashTable.get(num) ?? 0) + 1));
23+
24+
hashTable.forEach((count, number) => array.push({ number, count }));
25+
26+
array.sort((a, b) => b.count - a.count);
27+
28+
for (let i = 0; i < k; i++) answer.push(array[i].number);
29+
30+
return answer;
31+
};

0 commit comments

Comments
 (0)