-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.js
35 lines (28 loc) · 824 Bytes
/
main.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
// URL: https://leetcode.com/problems/top-k-frequent-words/
/**
* @param {string[]} words
* @param {number} k
* @return {string[]}
*/
var topKFrequent = function (words, k) {
let dict = {};
words.forEach((word) => {
dict[word] = dict[word] ?? 0;
dict[word]++;
});
let entries = Object.entries(dict).sort(([a, cA], [b, cB]) => {
const diff = cB - cA;
return diff === 0 ? (a > b ? 1 : -1) : diff;
});
let freq_words = [];
for (let i = 0; i < k; i++) freq_words.push(entries[i][0]);
return freq_words;
};
console.log(topKFrequent(["i", "love", "leetcode", "i", "love", "coding"], 2));
console.log(topKFrequent(["i", "love", "leetcode", "i", "love", "coding"], 3));
console.log(
topKFrequent(
["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"],
4
)
);