1. 题目描述
请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。
若队列为空,pop_front 和 max_value 需要返回 -1
示例 1:
输入:
[“MaxQueue”,“push_back”,“push_back”,“max_value”,“pop_front”,“max_value”]
[[],[1],[2],[],[],[]]
输出: [null,null,null,2,1,2]
示例 2:
输入:
[“MaxQueue”,“pop_front”,“max_value”]
[[],[],[]]
输出: [null,-1,-1]
限制:
1 <= push_back,pop_front,max_value的总操作数 <= 10000
1 <= value <= 10^5
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/dui-lie-de-zui-da-zhi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 题解
分析:
队列的出队和入队借助数组的方法可以达到O(1)时间的要求,求当前队列中的最大值,一种直观的想法是,每次遍历一遍队列找出最大值,这样在时间上需要O(n),不符合题目要求。
求队列最大值的第二种想法,用一个变量max记录队列中的最大值,但如果此时出队恰巧是max中记录的值,我们就不知道下一个最大值应该是谁了。
正确解法:额外开辟一个队列记为queue2,它是递减的,用于记录queue1顺序下的最大值、次大值…… , 每次找queue1的最大值时,取queue2的队首即可。
var MaxQueue = function() {
this.queue1 = [];
this.queue2 = [];
};
/**
* @return {number}
*/
MaxQueue.prototype.max_value = function() {
//取queue2的队首
if(this.queue2.length > 0){
return this.queue2[0];
}
return -1;
};
/**
* @param {number} value
* @return {void}
*/
MaxQueue.prototype.push_back = function(value) {
//入queue1
this.queue1.push(value);
//同时维护queue2
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() {
//出queue1
if(this.queue1.length <= 0){
return -1;
}
const value = this.queue1.shift();
//同时维护queue2
if(value === this.queue2[0]){
this.queue2.shift();
}
return value;
};
/**
* Your MaxQueue object will be instantiated and called as such:
* var obj = new MaxQueue()
* var param_1 = obj.max_value()
* obj.push_back(value)
* var param_3 = obj.pop_front()
*/