Skip to content

Commit 5119e34

Browse files
authoredSep 6, 2022
Update 239-sliding-window-maximum.js
1 parent a2d1651 commit 5119e34

File tree

1 file changed

+15
-17
lines changed

1 file changed

+15
-17
lines changed
 

‎239-sliding-window-maximum.js

Lines changed: 15 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,24 +4,22 @@
44
* @return {number[]}
55
*/
66
const maxSlidingWindow = function(nums, k) {
7-
let n = nums.length
8-
if (n === 0) {
9-
return nums
10-
}
11-
let result = []
12-
13-
let dq = []
14-
for (let i = 0; i < n; i++) {
15-
if (dq.length && dq[0] < i - k + 1) {
16-
dq.shift()
7+
const n = nums.length
8+
const stk = []
9+
const res = []
10+
11+
for(let i = 0; i < n; i++) {
12+
while(stk.length && stk[0] < i - k + 1) {
13+
stk.shift()
1714
}
18-
while (dq.length && nums[i] >= nums[dq[dq.length - 1]]) {
19-
dq.pop()
15+
while(stk.length && nums[stk[stk.length - 1]] <= nums[i]) {
16+
stk.pop()
2017
}
21-
dq.push(i)
22-
if (i - k + 1 >= 0) {
23-
result[i - k + 1] = nums[dq[0]]
18+
stk.push(i)
19+
if(i >= k - 1) {
20+
res.push(nums[stk[0]])
2421
}
2522
}
26-
return result
27-
}
23+
24+
return res
25+
};

0 commit comments

Comments
 (0)
Please sign in to comment.