Skip to content

Commit 4322a0e

Browse files
committedFeb 20, 2025
Add solution #239
1 parent 9ed96a7 commit 4322a0e

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,7 @@
215215
236|[Lowest Common Ancestor of a Binary Tree](./0236-lowest-common-ancestor-of-a-binary-tree.js)|Medium|
216216
237|[Delete Node in a Linked List](./0237-delete-node-in-a-linked-list.js)|Easy|
217217
238|[Product of Array Except Self](./0238-product-of-array-except-self.js)|Medium|
218+
239|[Sliding Window Maximum](./0239-sliding-window-maximum.js)|Hard|
218219
242|[Valid Anagram](./0242-valid-anagram.js)|Easy|
219220
257|[Binary Tree Paths](./0257-binary-tree-paths.js)|Easy|
220221
258|[Add Digits](./0258-add-digits.js)|Easy|
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* 239. Sliding Window Maximum
3+
* https://leetcode.com/problems/sliding-window-maximum/
4+
* Difficulty: Hard
5+
*
6+
* You are given an array of integers nums, there is a sliding window of size k which is moving
7+
* from the very left of the array to the very right. You can only see the k numbers in the
8+
* window. Each time the sliding window moves right by one position.
9+
*
10+
* Return the max sliding window.
11+
*/
12+
13+
/**
14+
* @param {number[]} nums
15+
* @param {number} k
16+
* @return {number[]}
17+
*/
18+
var maxSlidingWindow = function(nums, k) {
19+
const result = [];
20+
const queue = [];
21+
22+
for (let i = 0; i < nums.length; i++) {
23+
while (queue.length && queue[0] < i - k + 1) {
24+
queue.shift();
25+
}
26+
while (queue.length && nums[queue[queue.length - 1]] < nums[i]) {
27+
queue.pop();
28+
}
29+
queue.push(i);
30+
if (i >= k - 1) {
31+
result.push(nums[queue[0]]);
32+
}
33+
}
34+
35+
return result;
36+
};

0 commit comments

Comments
 (0)
Please sign in to comment.