algorithm-base/animation-simulation/单调队列单调栈/剑指offer59队列的最大值.md

104 lines
4.2 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
>
>
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
##
#### [ Offer 59 - II. ](https://leetcode-cn.com/problems/dui-lie-de-zui-da-zhi-lcof/)
####
max_value
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]
####
1
![](https://cdn.jsdelivr.net/gh/tan45du/github.io.phonto2@master/myphoto/队列的最大值.6bfapy4zf1g0.png)
![](https://img-blog.csdnimg.cn/20210319154950406.gif)
max_value
![](https://img-blog.csdnimg.cn/20210319154716931.gif)
1.
2.
3.
```java
class MaxQueue {
//普通队列
Queue<Integer> que;
//双端队列
Deque<Integer> deq;
public MaxQueue() {
que = new LinkedList<>();
deq = new LinkedList<>();
}
//获取最大值值,返回我们双端队列的对头即可,因为我们双端队列是单调递减的嘛
public int max_value() {
return deq.isEmpty() ? -1 : deq.peekFirst();
}
//入队操作
public void push_back(int value) {
que.offer(value);
//维护单调递减
while (!deq.isEmpty() && value > deq.peekLast()){
deq. pollLast();
}
deq.offerLast(value);
}
//返回队头元素此时有个细节我们需要用equals
//这里需要使用 equals() 代替 == 因为队列中存储的是 int 的包装类 Integer
public int pop_front() {
if(que.isEmpty()) return -1;
if (que.peek().equals(deq.peekFirst())) {
deq.pollFirst();
}
return que.poll();
}
}
```
###