From f618d35d8e39830d643177eda182944741427a6f Mon Sep 17 00:00:00 2001 From: Daixing Zhou <43519171+zhoudaixing@users.noreply.github.com> Date: Mon, 5 Feb 2024 15:59:20 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A00347=E5=89=8DK=E4=B8=AA?= =?UTF-8?q?=E9=AB=98=E9=A2=91=E5=85=83=E7=B4=A0=E7=9A=84JavaScript?= =?UTF-8?q?=E4=BD=BF=E7=94=A8=E4=BC=98=E5=85=88=E9=98=9F=E5=88=97=E5=BA=93?= =?UTF-8?q?=E7=9A=84=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0347.前K个高频元素.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/problems/0347.前K个高频元素.md b/problems/0347.前K个高频元素.md index 94b29eba..93d605f5 100644 --- a/problems/0347.前K个高频元素.md +++ b/problems/0347.前K个高频元素.md @@ -324,6 +324,34 @@ func topKFrequent(nums []int, k int) []int { ### JavaScript: +解法一: +Leetcode 提供了优先队列的库,具体文档可以参见 [@datastructures-js/priority-queue](https://github.com/datastructures-js/priority-queue/blob/v5/README.md)。 + +```js +var topKFrequent = function (nums, k) { + const map = new Map(); + const res = []; + //使用 map 统计元素出现频率 + for (const num of nums) { + map.set(num, (map.get(num) || 0) + 1); + } + //创建小顶堆 + const heap = new PriorityQueue({ + compare: (a, b) => a.value - b.value + }) + for (const [key, value] of map) { + heap.enqueue({ key, value }); + if (heap.size() > k) heap.dequeue(); + } + //处理输出 + while (heap.size()) res.push(heap.dequeue().key); + return res; +}; +``` + +解法二: +手写实现优先队列 + ```js // js 没有堆 需要自己构造 class Heap {