Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[fix][javascript] top-k-frequent-words #1583

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 13 additions & 11 deletions 多语言解法代码/solution_code.md
Original file line number Diff line number Diff line change
Expand Up @@ -64210,28 +64210,30 @@ var topKFrequent = function(words, k) {
wordToFreq.set(word, wordToFreq.get(word) + 1 || 1);
}

let pq = new PriorityQueue((a, b) => {
if (a.freq === b.freq) {
// 如果出现频率相同,按照字符串字典序排序
return b.word.localeCompare(a.word);
}
// 队列按照字符串出现频率从小到大排序
return a.freq - b.freq;
let pq = new PriorityQueue({
compare: (a, b) => {
if (a.freq === b.freq) {
// 如果出现频率相同,按照字符串字典序排序
return b.word.localeCompare(a.word);
}
// 队列按照字符串出现频率从小到大排序
return a.freq - b.freq;
},
});

// 按照字符串频率升序排序
for (let [word, freq] of wordToFreq.entries()) {
pq.offer({ word, freq });
if (pq.size > k) {
pq.enqueue({ word, freq });
if (pq.size() > k) {
// 维护出现频率最多的 k 个单词
pq.poll();
pq.dequeue();
}
}

// 把出现次数最多的 k 个字符串返回
let res = [];
while (!pq.isEmpty()) {
res.push(pq.poll().word);
res.push(pq.dequeue().word);
}
return res.reverse();
};
Expand Down