Skip to content

Commit 31c6b69

Browse files
authored
Update 347-top-k-frequent-elements.js
1 parent 3c9a8ca commit 31c6b69

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

347-top-k-frequent-elements.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,38 @@ const topKFrequent = function(nums, k) {
3131
return res
3232
};
3333

34+
// another
35+
36+
/**
37+
* @param {number[]} nums
38+
* @param {number} k
39+
* @return {number[]}
40+
*/
41+
const topKFrequent = function(nums, k) {
42+
const hash = {}
43+
for(let n of nums) {
44+
if(hash[n] == null) hash[n] = 0
45+
hash[n]++
46+
}
47+
const entries = Object.entries(hash)
48+
let min = Infinity, max = -Infinity
49+
const reverse = {}
50+
for(let [k, freq] of entries) {
51+
if(freq < min) min = freq
52+
if(freq > max) max = freq
53+
if(reverse[freq] == null) reverse[freq] = []
54+
reverse[freq].push(k)
55+
}
56+
const n = max - min + 1
57+
const arr = Array(n)
58+
let res = []
59+
let limit = max
60+
while(limit) {
61+
if(reverse[limit]) res.push(...reverse[limit])
62+
limit--
63+
if(res.length >= k) break
64+
}
65+
res.splice(k)
66+
return res
67+
};
68+

0 commit comments

Comments
 (0)