Leetcode 239. Sliding Window Maximum
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.
Example 1:
Input: nums = , 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
Example 2:
Input: nums = , k = 1
Output:
Example 3:
Input: nums = , k = 1
Output:
Example 4:
Input: nums = , k = 2
Output:
Example 5:
Input: nums = , k = 2
Output:
Constraints:
1 <= nums.length <= 105
-104 <= nums <= 104
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]