题目
- 请定义一个队列并实现函数max得到队列里的最大值,要求函数max、push_back和pop_front的时间复杂度都是O(1)。
- leetcode链接:https://leetcode-cn.com/problems/dui-lie-de-zui-da-zhi-lcof/
思路
- 单调队列
代码
// 请定义一个队列并实现函数 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]
var MaxQueue = function () {
this.queue = []
this.maxQueue = []
}
/**
* @return {number}
*/
MaxQueue.prototype.max_value = function () {
if (this.maxQueue.length) return this.maxQueue[0]
return -1
}
/**
* @param {number} value
* @return {void}
*/
MaxQueue.prototype.push_back = function (value) {
while (this.maxQueue.length && this.maxQueue[this.maxQueue.length - 1] < value) {
this.maxQueue.pop()
}
this.maxQueue.push(value)
this.queue.push(value)
}
/**
* @return {number}
*/
MaxQueue.prototype.pop_front = function () {
if (!this.queue.length) return -1
const s = this.queue.shift()
if (this.maxQueue.length && s === this.maxQueue[0]) {
this.maxQueue.shift()
}
return s
}
/**
* 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()
*/

860

被折叠的 条评论
为什么被折叠?



