Leetcode Leetcode 239. Sliding window maximum sliding window method combined with monotonous decreasing stack

Topic:

Given an integer array nums, a sliding window of size k moves from the leftmost side of the array to the rightmost side of the array. You can only see the k numbers in the sliding window. The sliding window only moves one position to the right at a time.
Returns the maximum value in the sliding window.

Example 1:

Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
Explanation:
The maximum position of the sliding window


[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

Example 2:

Input: nums = [1], k = 1
Output: [1]

Example 3:
Input: nums = [1,-1], k = 1
Output: [1,-1]

Example 4:
Input: nums = [9,11], k = 2
Output: [11]

Example 5:
Input: nums = [4,-2], k = 2
Output: [4]

Idea:
The idea at the beginning is actually to traverse the value of each window in the stack,
and each time the value in the max stack is returned to ans.
However, because the max function is too inefficient to run through the sample
with too much calculation, it is used The sliding window method simplifies the idea to avoid using the max function:

First traverse nums one by one, and maintain a monotonically decreasing stack.
First push the index of the first value into the stack.
If the value traversed later is smaller than the smallest value corresponding to the index in the stack, then directly index into the stack
as long as the value traversed later is greater than If the value corresponding to the index in the stack is larger or equal, the last value is removed
until the value traversed later is smaller than the value corresponding to the index in the stack, then the corresponding index is pushed onto the stack
to maintain a monotonically decreasing stack repeatedly

But since the length of k (sliding window) is fixed,
use the sliding window method.
If the index of the maximum value is smaller than the left boundary of the window (i-k), the leftmost value is removed
and i is the real-time right boundary, so no processing is required. Right margin

At the same time when the window exists (i + 1> k):
each traversal (moving window) adds the maximum value corresponding to the index of the maximum value in the stack to ans

Code:

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

        for i in range(len(nums)):
            while a and nums[a[-1]] <= nums[i]:
                a.pop()
            
            a.append(i)
        
            if a[0] <= i - k:
                a.popleft()
            if i + 1 >= k:
                ans.append(nums[a[0]])
        
        return ans

Result:

Guess you like

Origin blog.csdn.net/weixin_50791900/article/details/112130421