algorithm-base/animation-simulation/单调队列单调栈/滑动窗口的最大值.md

109 lines
5.2 KiB
Java
Raw Normal View History

2021-07-23 15:44:19 +00:00
> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
2021-03-20 11:38:55 +00:00
>
>
>
2021-07-23 15:44:19 +00:00
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
2021-03-20 11:38:55 +00:00
#### [ Offer 59 - I. ](https://leetcode-cn.com/problems/hua-dong-chuang-kou-de-zui-da-zhi-lcof/)
2021-03-20 05:38:47 +00:00
2021-03-19 08:36:59 +00:00
[ Offer 59 - II. ](https://leetcode-cn.com/problems/dui-lie-de-zui-da-zhi-lcof/)[155. 最小栈](https://leetcode-cn.com/problems/min-stack/),虽然这两个题目和该题类型不同,但是解题思路是一致的,都是很不错的题目,我认为做题,那些考察的很细的,解题思路很难想,即使想到,也不容易完全写出来的题目,才是能够大大提高我们编码能力的题目,希望能和大家一起进步。
****
![](https://img-blog.csdnimg.cn/20210319154950406.gif)
2021-07-23 15:44:19 +00:00
nums = [1,3,-1,-3,5,3,6,7], k = 3
2021-03-19 08:36:59 +00:00
![](https://img-blog.csdnimg.cn/20210319162114967.gif)
1.
2.
3.****
4.
5.
5.
```java
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
int len = nums.length;
if (len == 0) {
return nums;
}
int[] arr = new int[len - k + 1];
int arr_index = 0;
//我们需要维护一个单调递增的双向队列
Deque<Integer> deque = new LinkedList<>();
for (int i = 0; i < k; i++) {
while (!deque.isEmpty() && deque.peekLast() < nums[i]) {
deque.removeLast();
}
deque.offerLast(nums[i]);
}
arr[arr_index++] = deque.peekFirst();
for (int j = k; j < len; j++) {
if (nums[j - k] == deque.peekFirst()) {
deque.removeFirst();
}
while (!deque.isEmpty() && deque.peekLast() < nums[j]) {
deque.removeLast();
}
deque.offerLast(nums[j]);
arr[arr_index++] = deque.peekFirst();
}
return arr;
}
}
```
2021-07-27 18:26:32 +00:00
GO Code:
```go
func maxSlidingWindow(nums []int, k int) []int {
l := len(nums)
if l == 0 {
return nums
}
arr := []int{}
// 维护一个单调递减的双向队列
deque := []int{}
for i := 0; i < k; i++ {
for len(deque) != 0 && deque[len(deque) - 1] < nums[i] {
deque = deque[:len(deque) - 1]
}
deque = append(deque, nums[i])
}
arr = append(arr, deque[0])
for i := k; i < l; i++ {
if nums[i - k] == deque[0] {
deque = deque[1:]
}
for len(deque) != 0 && deque[len(deque) - 1] < nums[i] {
deque = deque[:len(deque) - 1]
}
deque = append(deque, nums[i])
arr = append(arr, deque[0])
}
return arr
}
```