Skip to content

Commit a094799

Browse files
committed
top k frequent elements solution
1 parent f863f03 commit a094799

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
var topKFrequent = function (nums, k) {
2+
// 1. count the frequency of each number in the array
3+
const map = new Map();
4+
5+
// iterating through the array to count how many times each num appears.
6+
for (const num of nums) {
7+
// if the num already exists in the map, increment its count
8+
if (map.has(num)) {
9+
map.set(num, map.get(num) + 1);
10+
} // otherwise, set it to 1
11+
else map.set(num, 1);
12+
}
13+
14+
// 2.create an array to store the freqeuncy numbers
15+
const freqArr = [];
16+
for (const [num, freq] of map) {
17+
freqArr.push([num, freq]);
18+
}
19+
// sort in descending order by frequency
20+
freqArr.sort((a, b) => b[1] - a[1]);
21+
return freqArr.slice(0, k).map(([num]) => num);
22+
};
23+
24+
// Time complexity: O(nlogn)
25+
// Space complexity: O(n)

0 commit comments

Comments
 (0)