Skip to content

Commit 3bb1935

Browse files
authored
Merge pull request neetcode-gh#638 from rutanshuj/patch-3
Update 347-Top-K-Frequent-Elements.js
2 parents 5bb5ea7 + b045b9e commit 3bb1935

File tree

1 file changed

+10
-10
lines changed

1 file changed

+10
-10
lines changed

javascript/347-Top-K-Frequent-Elements.js

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,26 +4,26 @@
44
* @return {number[]}
55
*/
66
var topKFrequent = function (nums, k) {
7-
let map = new Map();
7+
let map = {};
88
let res = [];
99
let bucket = Array.from({ length: nums.length + 1 }, () => []); // to create unique arrays
1010

1111
// 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);
12+
for (const n of nums) {
13+
map[n] = (n in map) ? 1 + map[n] : 1;
1414
}
1515

16-
// Poppulate the bucket with numbers in frequency
16+
// Populate the bucket with numbers in frequency
1717
// as the index of the bucket
18-
for (const [key, value] of map.entries()) {
19-
bucket[value].push(key);
18+
for(const c in map){
19+
bucket[map[c]].push(c);
2020
}
21-
21+
2222
for (let i = bucket.length - 1; i >= 0; i--) {
2323
if (bucket[i].length > 0) {
24-
for (let n of bucket[i]) {
25-
res.push(n);
26-
if (res.length === k) return res;
24+
bucket[i].forEach((elem)=> res.push(elem));
25+
if(k == res.length){
26+
return res;
2727
}
2828
}
2929
}

0 commit comments

Comments
 (0)