马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
Problem
You are given an array of integers 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.
Algorithm
Monotonic Queue. A monotonic queue is used to store a decreasing sequence. If the current element is greater than the last element of the queue, we remove elements from the queue until the last element of the queue is smaller than the current element, or the queue becomes empty. Then, the current element is stored in the queue. The element at the front of the queue is also controlled by the length k.
Code
- class Solution:
- def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
- if not nums or not k:
- return []
-
- nums_size = len(nums)
- Q, L, R = [0] * nums_size, 0, 0
- ans = [nums[0]] * nums_size
- for i in range(1, nums_size):
- while L <= R and nums[Q[R]] <= nums[i]:
- R -= 1
- R += 1
- Q[R] = i
- if i - Q[L] + 1 > k:
- L += 1
- ans[i] = nums[Q[L]]
-
- return ans[k-1:]
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
|