leetcode239 Sliding Window Maximum-zh
# 239. 滑动窗口最大值 (opens new window)
English Version (opens new window)
# 题目描述
给你一个整数数组 nums
,有一个大小为 k
的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k
个数字。滑动窗口每次只向右移动一位。
返回滑动窗口中的最大值。
示例 1:
输入:nums = [1,3,-1,-3,5,3,6,7], k = 3 输出:[3,3,5,5,6,7] 解释: 滑动窗口的位置 最大值 --------------- ----- [1 3 -1] -3 5 3 6 7 3 1 [3 -1 -3] 5 3 6 7 3 1 3 [-1 -3 5] 3 6 7 5 1 3 -1 [-3 5 3] 6 7 5 1 3 -1 -3 [5 3 6] 7 6 1 3 -1 -3 5 [3 6 7] 7
示例 2:
输入:nums = [1], k = 1 输出:[1]
示例 3:
输入:nums = [1,-1], k = 1 输出:[1,-1]
示例 4:
输入:nums = [9,11], k = 2 输出:[11]
示例 5:
输入:nums = [4,-2], k = 2 输出:[4]
提示:
1 <= nums.length <= 105
-104 <= nums[i] <= 104
1 <= k <= nums.length
# 解法
# Python3
1
# Java
1
# JavaScript
/**
* @param {number[]} nums
* @param {number} k
* @return {number[]}
*/
var maxSlidingWindow = function (nums, k) {
let len = nums.length;
if (len < k) return [];
let res = [], win = [];
for (let i = 0; i < k; i++) {
while (win.length > 0 && nums[i] >= nums[win[win.length - 1]])
win.pop();
win.push(i);
}
res.push(nums[win[0]]);
for (let i = k; i < len; i++) {
while (win.length > 0 && nums[i] >= nums[win[win.length - 1]])
win.pop();
if (win.length > 0 && win[0] < i - k + 1)
win.shift();
win.push(i);
res.push(nums[win[0]]);
}
return res;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# ...
1
编辑 (opens new window)
上次更新: 2021/10/30, 12:58:38