Merge pull request #2436 from zhoudaixing/topkelements-JS-patch

增加 0347前K个高频元素 JavaScript 使用优先队列库的解法
This commit is contained in:
程序员Carl
2024-02-16 09:17:45 +08:00
committed by GitHub

View File

@ -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 {