# 剑指 Offer 59 - II. 队列的最大值

## 题目描述

[“MaxQueue”,“push_back”,“push_back”,“max_value”,“pop_front”,“max_value”]
[[],[1],[2],[],[],[]]

[“MaxQueue”,“pop_front”,“max_value”]
[[],[],[]]

## 题解

class MaxQueue {

//队列q用于获取pop()的返回值
Queue<Integer> q;
//双端队列尾d部进(push)，尾部出(pollLast,用于移除比待push的value小的值),头部出(max_value)
Deque<Integer> d;

public MaxQueue() {
}

public int max_value() {
if(d.isEmpty()){
return -1;
}
//因为双端队列是一个递减序列，所以只需要获取队列的头结点即可获得队列最大值
return d.peekFirst();
}

public void push_back(int value) {
//把双端队列d中所有比value小的值从尾部出队，以构成一个递减序列
while(!d.isEmpty()&&d.peekLast()<value){
d.pollLast();
}
//把value存入p和d中
d.offerLast(value);
q.offer(value);
}

public int pop_front() {
if(q.isEmpty()){
return -1;
}
int ans = q.poll();
if(ans==d.peekFirst()){
d.pollFirst();
}
return ans;
}
}

/**
* Your MaxQueue object will be instantiated and called as such:
* MaxQueue obj = new MaxQueue();
* int param_1 = obj.max_value();
* obj.push_back(value);
* int param_3 = obj.pop_front();
*/


02-24 354
02-29 282
03-15 106
03-07 141
06-06 87
02-14 186