-
Notifications
You must be signed in to change notification settings - Fork 41
/
solution.js
39 lines (34 loc) · 963 Bytes
/
solution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* @param {string[]} words
* @param {number} k
* @return {string[]}
*/
var topKFrequent = function (words, k) {
const countMap = {};
for (let i = 0; i < words.length; i++) {
countMap[words[i]] = (countMap[words[i]] || 0) + 1;
}
const groupByFrenquency = Object.keys(countMap).reduce((obj, word) => {
const frenquency = countMap[word];
if (!obj[frenquency]) {
obj[frenquency] = [
word, ];
} else {
obj[frenquency].push(word);
}
return obj;
}, {});
const counts = Object.keys(groupByFrenquency).sort((a, b) => +b - (-a));
const result = [];
for (let i = 0; i < counts.length; i++) {
if (k === 0) {
break;
}
const words = groupByFrenquency[counts[i]].sort();
while (k > 0 && words.length > 0) {
result.push(words.shift());
k--;
}
}
return result;
};