Closed labuladong closed 1 year ago
# Aug 16
# LC 239 Sliding Window Max
# Monotonic queue maintains largest element efficiently
# Base on deque (doubly linked list) pop and append in two directions
# pop all elements smaller than current element
from collections import deque
class M_Queue:
def __init__(self):
self.nums = deque()
def push(self, ele):
while len(self.nums) > 0 and self.nums[-1] < ele:
self.nums.pop()
self.nums.append(ele)
def pop(self, ele):
if ele == self.nums[0]:
self.nums.popleft()
def max(self):
return self.nums[0]
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
win = M_Queue()
res = []
for idx, i in enumerate(nums):
if idx < k - 1:
win.push(i)
else:
win.push(i)
res.append(win.max())
win.pop(nums[idx - k + 1])
return res
本期打卡已结算完成。报名最新一期的打卡活动 点这里