From eed4e116c8d34ac2d1e24834c487f2df164cf792 Mon Sep 17 00:00:00 2001 From: wangruilong Date: Wed, 24 Apr 2024 16:07:24 +0800 Subject: [PATCH] fix(javascript): top-k-frequent-words --- .../solution_code.md" | 24 ++++++++++--------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git "a/\345\244\232\350\257\255\350\250\200\350\247\243\346\263\225\344\273\243\347\240\201/solution_code.md" "b/\345\244\232\350\257\255\350\250\200\350\247\243\346\263\225\344\273\243\347\240\201/solution_code.md" index 4a577d5958..2eba4aa44e 100644 --- "a/\345\244\232\350\257\255\350\250\200\350\247\243\346\263\225\344\273\243\347\240\201/solution_code.md" +++ "b/\345\244\232\350\257\255\350\250\200\350\247\243\346\263\225\344\273\243\347\240\201/solution_code.md" @@ -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(); };