JS堆的使用(datastructures-js/priority-queue、简单版手写)

datastructures-js/priority-queue的基本使用

力扣JS内置datastructures-js/priority-queue,本质上是使用堆实现的。
详情查看官网 https://github.com/datastructures-js/priority-queue

以力扣295为例

1 新增
var MedianFinder = function() {
    this.left = new MaxPriorityQueue();
    this.right = new MinPriorityQueue();
};

2 添加元素 入队
this.left.enqueue(num);

3 删除堆顶
this.right.dequeue(this.right.front())
// removes and returns the element with highest priority in the queue in O(log(n)) runtime.

4 isEmpty
5 size
6 clear

“手写”

实现没有利用堆的性质,而是直接使用数组和排序,导致性能较差。

这里的堆性能很差,因为直接调用了数组的sort,这是一个 O(n log n) 的操作。
对于优先队列(堆)来说,插入操作的时间复杂度应该是 O(log n),而不是 O(n log n)。

使用 shift() 方法从数组头部删除元素,这是一个 O(n) 的操作,因为需要移动数组中的所有元素。
对于优先队列来说,删除操作的时间复杂度应该是 O(log n)。

class MyPriorityQueue {
    constructor(compare) {
        this.heap = [];
        this.compare = compare;
    }

    size() {
        return this.heap.length;
    }

    enqueue(item) {
        this.heap.push(item);
        this.heap.sort(this.compare);
    }

    dequeue() {
        return this.heap.shift();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值