File tree 2 files changed +60
-0
lines changed
2 files changed +60
-0
lines changed Original file line number Diff line number Diff line change 95
95
| 235| [ 二叉搜索树的最近公共祖先] ( https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-search-tree/ ) | [ JavaScript] ( ./algorithms/lowest-common-ancestor-of-a-binary-search-tree.js ) | Easy|
96
96
| 236| [ 二叉树的最近公共祖先] ( https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/ ) | [ JavaScript] ( ./algorithms/lowest-common-ancestor-of-a-binary-tree.js ) | Medium|
97
97
| 237| [ 删除链表中的节点] ( https://leetcode-cn.com/problems/delete-node-in-a-linked-list/ ) | [ JavaScript] ( ./algorithms/delete-node-in-a-linked-list.js ) | Easy|
98
+ | 239| [ 滑动窗口最大值] ( https://leetcode.cn/problems/sliding-window-maximum/ ) | [ JavaScript] ( ./algorithms/sliding-window-maximum.js ) | Hard|
98
99
| 242| [ 有效的字母异位词] ( https://leetcode.cn/problems/valid-anagram/ ) | [ JavaScript] ( ./algorithms/valid-anagram.js ) | Easy|
99
100
| 257| [ 二叉树的所有路径] ( https://leetcode.cn/problems/binary-tree-paths/ ) | [ JavaScript] ( ./algorithms/binary-tree-paths.js ) | Easy|
100
101
| 283| [ 移动零] ( https://leetcode.cn/problems/move-zeroes/ ) | [ JavaScript] ( ./algorithms/move-zeroes.js ) | Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number[] } nums
3
+ * @param {number } k
4
+ * @return {number[] }
5
+ */
6
+ var maxSlidingWindow = function ( nums , k ) {
7
+ // 单调队列
8
+ const deque = new Deque ( ) ;
9
+ const result = [ ] ;
10
+
11
+ // 先将前 k 个元素放进队列
12
+ for ( let i = 0 ; i < k ; i ++ ) {
13
+ deque . push ( nums [ i ] ) ;
14
+ }
15
+ // 记录前 k 个元素的最大值
16
+ result . push ( deque . front ( ) ) ;
17
+
18
+ for ( let i = k ; i < nums . length ; i ++ ) {
19
+ const curr = nums [ i ] ;
20
+ // 滑动窗口移除最前面元素
21
+ deque . pop ( nums [ i - k ] ) ;
22
+ // 滑动窗口前加入最后面的元素
23
+ deque . push ( curr ) ;
24
+ // 记录对应的最大值
25
+ result . push ( deque . front ( ) ) ;
26
+ }
27
+
28
+ return result ;
29
+ } ;
30
+
31
+ /**
32
+ * 单调队列 (递减)
33
+ */
34
+ class Deque {
35
+ constructor ( ) {
36
+ this . queue = [ ] ;
37
+ }
38
+
39
+ push ( val ) {
40
+ if ( this . queue . length === 0 ) {
41
+ this . queue . push ( val ) ;
42
+ } else {
43
+ while ( this . queue . length > 0 && val > this . queue . at ( - 1 ) ) {
44
+ this . queue . pop ( ) ;
45
+ }
46
+ this . queue . push ( val ) ;
47
+ }
48
+ }
49
+
50
+ pop ( val ) {
51
+ if ( val === this . front ( ) ) {
52
+ this . queue . shift ( ) ;
53
+ }
54
+ }
55
+
56
+ front ( ) {
57
+ return this . queue [ 0 ] ;
58
+ }
59
+ }
You can’t perform that action at this time.
0 commit comments