优先级队列(头条面试题)

15 篇文章 0 订阅
11 篇文章 0 订阅

来源:微信公众号:算法面试题

 

              扫码开启算法之旅

 

//实现一个优先级队列,此队列具有enqueue(val,prior)和dequeue()两种操作,分别代表入队和出队。
//其中enqueue(val,prior)第一个参数val为为值,第二个参数prior为优先级(prior越大,优先级越高),优先级越高越先出队
//dequeue()出队操作,每调用一次从队列中找到一个优先级最高的元素出队,并返回此元素的值(val)
//要求:在O(logn)时间复杂度内完成两种操作
class PriorityQueue {
	constructor() {
		//数组,入队的元素保存在这里,
		//每进行一次入队或出队操作,都需重新调整数组为大顶堆
		this.arr = [];
	}

	//入队
	enqueue(val, prior) {
		this.arr.push({
			val: val,
			prior: prior
		});
		let cur = this.arr.length - 1;
		let temp = this.arr[cur];
		//对刚入队的那个元素实施上浮操作,即重新调整数组为大顶堆
		for(let i = Math.floor((cur - 1) / 2); i >= 0; i = Math.floor((i - 1) / 2)) {
			if(temp.prior > this.arr[i].prior) {
				this.arr[cur] = this.arr[i];
				cur = i;
			} else break;
		}
		this.arr[cur] = temp;
	}

	//出队
	dequeue() {
		if(this.arr.length === 0) throw new Error("队列为空,不能出队");
		//大顶堆保证了第一个元素的优先级永远最高,是要出队的元素

		//将第一个元素的值缓存,以便返回
		let res = this.arr[0].val;

		//用队尾元素元素覆盖第一个元素
		this.arr[0] = this.arr[this.arr.length - 1];

		//将队列长度-1
		this.arr.length -= 1;

		//重新调整队列为大顶堆
		let cur = 0,
			len = this.arr.length;
		let temp = this.arr[0];
		for(let i = 2 * cur + 1; i < len; i = 2 * cur + 1) {
			if(i + 1 < len && this.arr[i].prior < this.arr[i + 1].prior)
				i++;
			if(temp.prior < this.arr[i].prior) {
				this.arr[cur] = this.arr[i];
				cur = i;
			} else break;
		}
		this.arr[cur] = temp;

		//返回结果
		return res;
	}
}

let p = new PriorityQueue();
p.enqueue(5, 6);
p.enqueue(2, 100);
p.enqueue(90, 1);

console.log(p.dequeue());//2
console.log(p.dequeue());//5
console.log(p.dequeue());//90

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值