File tree Expand file tree Collapse file tree 2 files changed +35
-0
lines changed Expand file tree Collapse file tree 2 files changed +35
-0
lines changed Original file line number Diff line number Diff line change 79
79
232. 用栈实现队列
80
80
234. 回文链表
81
81
236. 二叉树的最近公共祖先
82
+ 239. 滑动窗口最大值
82
83
279. 完全平方数
83
84
283. 移动零
84
85
300. 最长上升子序列
Original file line number Diff line number Diff line change
1
+ // 239. 滑动窗口最大值
2
+
3
+
4
+ /*
5
+ 剑指offer 64.滑动窗口的最大值
6
+ 双端队列,单调递减队列:
7
+ 1、根据数组长度和窗口大小,初始化结果数组长度
8
+ 2、队列存放的是索引,既能通过索引判断是否在窗口内,也能通过索引获取元素值
9
+ 3、遍历数组元素
10
+ 1)当队列不为空 且 当前元素大于等于队尾元素,则弹出队尾元素,循环处理
11
+ 2)当前元素加入队尾。此时队列是单调递减队列
12
+ 3)检查队首索引是否在窗口内,不在窗口内则弹出队首索引
13
+ 4)当前滑动窗口大小为k时,队首索引的元素是窗口内的最大值,加入结果数组
14
+ */
15
+ class Solution {
16
+ public int [] maxSlidingWindow (int [] nums , int k ) {
17
+ int n = nums .length ;
18
+ int [] res = new int [n - k + 1 ];
19
+ Deque <Integer > queue = new ArrayDeque <>();
20
+ for (int i = 0 ; i < n ; i ++) {
21
+ while (!queue .isEmpty () && nums [i ] >= nums [queue .peekLast ()]) {
22
+ queue .pollLast ();
23
+ }
24
+ queue .addLast (i );
25
+ if (queue .peek () == i - k ) {
26
+ queue .poll ();
27
+ }
28
+ if (i + 1 >= k ) {
29
+ res [i + 1 - k ] = nums [queue .peek ()];
30
+ }
31
+ }
32
+ return res ;
33
+ }
34
+ }
You can’t perform that action at this time.
0 commit comments