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();
}
}