- 请定义一个队列并实现函数 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、看清题目:
3、解题思路:
(1)用数组模拟队列
(2)数据队列在取出首位之后,如何保证最大值队列里的首位为剩下数据队列的最大值???这是关键
4、代码
var MaxQueue = function() { this.queue = [];//队列用于存放数据 this.deque = [];//双端队列用于存放maxValue};/** * @return {number} */MaxQueue.prototype.max_value = function() { return this.deque[0] ? this.deque[0] : -1 ;};/** * @param {number} value * @return {void} */MaxQueue.prototype.push_back = function(value) { while(this.deque.length && this.deque[this.deque.length-1]<value){ this.deque.pop(); } this.deque.push(value); this.queue.push(value);};/** * @return {number} */MaxQueue.prototype.pop_front = function() { if(this.queue.length==0) return -1; if(this.queue[0] == this.deque[0]){ this.deque.shift(); } return this.queue.shift()};