题目
请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。
若队列为空,pop_front 和 max_value 需要返回 -1
代码实现
单调双端队列
class MaxQueue {
//queue1用于存数据,queue2用于存最大值
Deque<Integer> queue1;
Deque<Integer> queue2;
public MaxQueue() {
queue1 = new LinkedList<>();
queue2 = new LinkedList<>();
}
public int max_value() {
return queue2.isEmpty()?-1:queue2.peek();
}
public void push_back(int value) {
queue1.offer(value);
while (!queue2.isEmpty() && queue2.getLast() < value){
queue2.removeLast();
}
queue2.offer(value);
}
public int pop_front() {
if (queue1.isEmpty()){
return -1;
}
int pop = queue1.pop();
if (queue2.peek() == pop){
queue2.removeFirst();
}
return pop;
}
}