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
class MaxQueue {
public Queue<Integer> queue=new LinkedList<>();
public Deque<Integer> deque=new LinkedList<>();
public MaxQueue() {
}
public int max_value() {
if(!deque.isEmpty()){
return deque.peekFirst();
}
return -1;
}
public void push_back(int value) {
while(!deque.isEmpty()&&deque.peekLast()<value){
deque.pollLast();
}
deque.offerLast(value);
queue.offer(value);
}
public int pop_front() {
if(queue.isEmpty()){
return -1;
}
int value=queue.poll();
if(!deque.isEmpty()&&value==deque.peekFirst()){
deque.pollFirst();
}
return value;
}
}
/**
* 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();
*/