难度:中等
题目描述:
请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。
若队列为空,pop_front 和 max_value 需要返回 -1
示例:
输入:["MaxQueue","push_back","push_back","max_value","pop_front","max_value"][[],[1],[2],[],[],[]]输出: [null,null,null,2,1,2]
解题思路:
var MaxQueue = function() {this.queue1 = [];this.queue2 = [];};/*** @return {number}*/MaxQueue.prototype.max_value = function() {if (this.queue2.length) {return this.queue2[0];}return -1;};/*** @param {number} value* @return {void}*/MaxQueue.prototype.push_back = function(value) {this.queue1.push(value);while (this.queue2.length && this.queue2[this.queue2.length - 1] < value) {this.queue2.pop();}this.queue2.push(value);};/*** @return {number}*/MaxQueue.prototype.pop_front = function() {if (!this.queue1.length) {return -1;}const value = this.queue1.shift();if (value === this.queue2[0]) {this.queue2.shift();}return value;};
