/**
* 实现优先队列
* 使用:let qeen = new PriorityQueue((a, b) => b - a);
* qeen.push(3);
* qeen.push(1);
* qeen.push(5);
* console.log(qeen.data);// [5, 3, 1]
* */
class myPriorityQueue {
/** 构造 */
constructor(compare) {
if (typeof compare !== "function") {
throw new Error("compare function required!");
}
this.data = [];
this.compare = compare;
}
/** 查询插入位置 */
search(target) {
let left = 0;
let right = this.data.length;
while (left < right) {
let mid = left + ((right - left) >> 1);
if (this.compare(this.data[mid], target) > 0) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
/** 添加 */
push(item) {
let index = this.search(item);
this.data.splice(index, 0, item);
return this.data.length;
}
/** 弹出 */
pop() {
return this.data.pop();
}
/** 查看 */
peek() {
return this.data[this.data.length - 1];
}
/** 是否为空 */
isEmpty() {
return this.data.length === 0;
}
}
实现优先队列
最新推荐文章于 2024-07-16 16:43:05 发布