Skip to content

Commit eed4e11

Browse files
author
wangruilong
committed
fix(javascript): top-k-frequent-words
1 parent 4f44711 commit eed4e11

File tree

1 file changed

+13
-11
lines changed

1 file changed

+13
-11
lines changed

多语言解法代码/solution_code.md

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -64210,28 +64210,30 @@ var topKFrequent = function(words, k) {
6421064210
wordToFreq.set(word, wordToFreq.get(word) + 1 || 1);
6421164211
}
6421264212

64213-
let pq = new PriorityQueue((a, b) => {
64214-
if (a.freq === b.freq) {
64215-
// 如果出现频率相同,按照字符串字典序排序
64216-
return b.word.localeCompare(a.word);
64217-
}
64218-
// 队列按照字符串出现频率从小到大排序
64219-
return a.freq - b.freq;
64213+
let pq = new PriorityQueue({
64214+
compare: (a, b) => {
64215+
if (a.freq === b.freq) {
64216+
// 如果出现频率相同,按照字符串字典序排序
64217+
return b.word.localeCompare(a.word);
64218+
}
64219+
// 队列按照字符串出现频率从小到大排序
64220+
return a.freq - b.freq;
64221+
},
6422064222
});
6422164223

6422264224
// 按照字符串频率升序排序
6422364225
for (let [word, freq] of wordToFreq.entries()) {
64224-
pq.offer({ word, freq });
64225-
if (pq.size > k) {
64226+
pq.enqueue({ word, freq });
64227+
if (pq.size() > k) {
6422664228
// 维护出现频率最多的 k 个单词
64227-
pq.poll();
64229+
pq.dequeue();
6422864230
}
6422964231
}
6423064232

6423164233
// 把出现次数最多的 k 个字符串返回
6423264234
let res = [];
6423364235
while (!pq.isEmpty()) {
64234-
res.push(pq.poll().word);
64236+
res.push(pq.dequeue().word);
6423564237
}
6423664238
return res.reverse();
6423764239
};

0 commit comments

Comments
 (0)