Skip to content

Commit 22e9014

Browse files
committed
239. 滑动窗口最大值
1 parent 326d843 commit 22e9014

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@
9595
|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|
9696
|236|[二叉树的最近公共祖先](https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/)|[JavaScript](./algorithms/lowest-common-ancestor-of-a-binary-tree.js)|Medium|
9797
|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|
9899
|242|[有效的字母异位词](https://leetcode.cn/problems/valid-anagram/)|[JavaScript](./algorithms/valid-anagram.js)|Easy|
99100
|257|[二叉树的所有路径](https://leetcode.cn/problems/binary-tree-paths/)|[JavaScript](./algorithms/binary-tree-paths.js)|Easy|
100101
|283|[移动零](https://leetcode.cn/problems/move-zeroes/)|[JavaScript](./algorithms/move-zeroes.js)|Easy|

Diff for: algorithms/sliding-window-maximum.js

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
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+
}

0 commit comments

Comments
 (0)