题链接:https://leetcode-cn.com/problems/dui-lie-de-zui-da-zhi-lcof/
类似题:栈的最小值(辅助栈)
题描述:
解题思路:
利用 numQueue 保存输入的变量,利用辅助队列 assQueue 维护一个递减队列,队首存放 numQueue 中的最大值。
(1)max_value:
如果队列为空,返回 -1,否则返回 assQueue 队首元素。
(2)push_back:
当一个新的元素 T 要进入 numQueue 时,将 assQueue 队列中比 T 小的元素出队,因为此时前面比 T 小的元素都不会成为最大值。
然后压入 numQueue 和 assQueue。
(3)pop_front:
如果队列为空,返回 -1,否则如果 numQueue 要出队的元素与 assQueue 队首元素相同,则 assQueue 队首元素也要出队。
代码实现:
var MaxQueue = function() {
this.numQueue = [];
this.assQueue = [];
};
/**
* @return {number}
*/
MaxQueue.prototype.max_value = function() {
if (this.assQueue.length == 0) {
return -1;
}
return this.assQueue[0];
};
/**
* @param {number} value
* @return {void}
*/
MaxQueue.prototype.push_back = function(value) {
while (this.assQueue[this.assQueue.length - 1] < value) {
this.assQueue.length -= 1;
}
this.assQueue.push(value);
this.numQueue.push(value);
};
/**
* @return {number}
*/
MaxQueue.prototype.pop_front = function() {
if (this.numQueue.length == 0) {
return -1;
}
let t = this.numQueue.shift();
if (t == this.assQueue[0]) {
this.assQueue.shift();
}
return t;
};
时间复杂度:O(1)
空间复杂度:O(n)