题目链接
题目(中等)
请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。
题解
队列
let MaxQueue = function () {
this.queue = []; // 用一个正常数组存取每次 push 进来的元素
this.maxQueue = []; // 该队列专门为了简化 max_value 这个 API,称它为单调递减队列
};
/**
* @return {number}
*/
MaxQueue.prototype.max_value = function () {
return this.maxQueue.length ? this.maxQueue[0] : -1;
};
/**
* @param {number} value
* @return {void}
*/
MaxQueue.prototype.push_back = function (value) {
this.queue.push(value);
while (this.maxQueue.length && this.maxQueue[this.maxQueue.length - 1] < value) {
this.maxQueue.pop();
}
this.maxQueue.push(value);
};
/**
* @return {number}
*/
MaxQueue.prototype.pop_front = function () {
if (!this.queue.length) {
return -1;
}
const value = this.queue.shift();
if (value === this.maxQueue[0]) {
this.maxQueue.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()
*/