Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right.
- You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.
- """
- """
- Idea: using deque
- 1. Deque right pointer should NEVER point to elements smaller than current element
- 2. Deque left pointer should NEVER point to elements outside our sliding window
- """
- from collections import deque
- class Solution:
- def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
- q = deque()
- ans = []
- for i, v in enumerate(nums):
- if q and i - k + 1 > q[0]:
- q.popleft() # remove index if out of window left
- while q and nums[q[-1]] <= v: # `<=`, not `<`, to ensure the bigger index stored in deque
- q.pop()
- q.append(i)
- if i >= k - 1:
- ans.append(nums[q[0]])
- return ans
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement