Skip to content

239. 滑动窗口最大值

给你一个整数数组 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]

提示:

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • 1 <= k <= nums.length

解答

代码

python
class Solution:
    def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
        n = len(nums)
        
        hh = 0
        tt = -1
        q = [0] * n
        ans = []

        for i in range(n):
            if hh <= tt and q[hh] <= i - k:
                hh += 1

            while hh <= tt and nums[q[tt]] <= nums[i]:
                tt -= 1
            
            tt += 1
            q[tt] = i

            if i >= k - 1:
                ans.append(nums[q[hh]])
        
        return ans

这里一定要注意不能用 q.append(i)

STL 方法

python
class Solution:
    def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
        ans = []
        q = deque()

        for i, x in enumerate(nums):
            while q and nums[q[-1]] <= x:
                q.pop()
            q.append(i)

            while i - q[0] + 1 > k:
                q.popleft()

            if i >= k - 1:
                ans.append(nums[q[0]])
        
        return ans

Released under the MIT License.