classSolution:defmaxSlidingWindow(self, nums: List[int], k:int)-> List[int]:# deque保存当前最大值,和下一个可能的最大值。未形成窗口和形成窗口分别放在两个循环,时间复杂度o(n)),空间复杂度o(1)ifnot nums:return[]
deque=collections.deque()
n,res=len(nums),[]for i inrange(k):while deque and nums[i]> deque[-1]:
deque.pop()
deque.append(nums[i])
res.append(deque[0])for i inrange(k,n):if nums[i-k]== deque[0]:
deque.popleft()while deque and nums[i]> deque[-1]:
deque.pop()
deque.append(nums[i])
res.append(deque[0])return res
剑指offer59-Ⅱ 队列的最大值
import queue
classMaxQueue:def__init__(self):
self.deque=queue.deque()
self.queue=queue.Queue()# 定义dequedefmax_value(self)->int:ifnot self.deque:return-1else:return self.deque[0]defpush_back(self, value:int)->None:while self.deque and value > self.deque[-1]:
self.deque.pop()
self.deque.append(value)
self.queue.put(value)defpop_front(self)->int:ifnot self.deque:return-1
ans = self.queue.get()if ans == self.deque[0]:
self.deque.popleft()return ans
# Your MaxQueue object will be instantiated and called as such:# obj = MaxQueue()# param_1 = obj.max_value()# obj.push_back(value)# param_3 = obj.pop_front()