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 {