Skip to content

Commit 048ed97

Browse files
authored
Temporary duplicate
1 parent 7401b3e commit 048ed97

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} k
4+
* @return {number[]}
5+
*/
6+
var topKFrequent = function(nums, k) {
7+
let map = new Map();
8+
let res = [];
9+
let bucket = Array.from({ length: nums.length + 1 }, () => []); // to create unique arrays
10+
11+
// storing frequency of numbers in a map
12+
for (let n of nums) {
13+
map.set(n, (map.has(n) ? 1 + map.get(n) : 1))
14+
}
15+
16+
// Poppulate the bucket with numbers in frequency
17+
// as the index of the bucket
18+
for (const [key, value] of map.entries()) {
19+
bucket[value].push(key);
20+
}
21+
22+
for (let i = bucket.length - 1; i >= 0; i--) {
23+
if (bucket[i].length > 0) {
24+
for (let n of bucket[i]) {
25+
res.push(n);
26+
if (res.length === k)
27+
return res;
28+
}
29+
}
30+
}
31+
};

0 commit comments

Comments
 (0)