Skip to content

Commit b045b9e

Browse files
authored
Update 347-Top-K-Frequent-Elements.js
1) Last inner "for" loop, checking whether threshold and response array 's lengths are equal, does not need condition as the response can be in any order, hence "if-condition" can be placed outside. 2) Instead of Map functions we can used basic JS object functions. 3) Few other changes - Spelling mistake(s), variable declaration changes in for-loop.
1 parent 5161ef7 commit b045b9e

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)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy