Leetcode 239. Sliding Window Maximum
本帖最后由 Seawolf 于 2020-7-30 11:46 编辑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.
Follow up:
Could you solve it in linear time?
Example:
Input: nums = , and k = 3
Output:
Explanation:
Window position Max
--------------- -----
-35367 3
1 5367 3
13 [-1-35] 367 5
13-1 [-353] 67 5
13-1-3 7 6
13-1-35 7
Constraints:
1 <= nums.length <= 10^5
-10^4 <= nums <= 10^4
1 <= k <= nums.length
给定一个数组 nums,有一个大小为k;的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k个数字。滑动窗口每次只向右移动一位。
返回滑动窗口中的最大值。
进阶:
你能在线性时间复杂度内解决此题吗?
示例:
输入: nums = , 和 k = 3
输出:
解释:
滑动窗口的位置 最大值
--------------- -----
-35367 3
1 5367 3
13 [-1-35] 367 5
13-1 [-353] 67 5
13-1-3 7 6
13-1-35 7
提示:
1 <= nums.length <= 10^5
-10^4<= nums<= 10^4
1 <= k<= nums.length
from collections import deque
class Solution:
def maxSlidingWindow(self, nums: List, k: int) -> List:
queue = deque()
res = []
if len(nums) == 0:
return res
for i in range(k - 1):
self.indeque(queue, nums)
for i in range(k - 1, len(nums)):
self.indeque(queue, nums)
res.append(queue)
self.outdeque(queue, nums)
return res
def indeque(self, queue: List, num: int) -> None:
while len(queue) != 0 and queue[-1] < num:
queue.pop()
queue.append(num)
def outdeque(self, queue: List, num: int) -> None:
if queue == num:
queue.popleft()
页:
[1]