第一题 剑指 Offer 59 - II. 队列的最大值https://leetcode-cn.com/problems/dui-lie-de-zui-da-zhi-lcof/
class MaxQueue:
def __init__(self):
self.queue = []
self.deque = []
def max_value(self) -> int:
return self.deque[0] if self.deque else -1
def push_back(self, value: int) -> None:
self.queue.append(value)
while self.deque and self.deque[-1] < value:
self.deque.pop()
self.deque.append(value)
def pop_front(self) -> int:
if not self.queue: return -1
val = self.queue.pop(0)
if val == self.deque[0]:
self.deque.pop(0)
return val
# 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()
这一题比较简单 通过列表模拟队列的入和出 也可以使用collection.queue
第二题 剑指 Offer 59 - I. 滑动窗口的最大值https://leetcode-cn.com/problems/hua-dong-chuang-kou-de-zui-da-zhi-lcof/
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
# 暴力解法
# if not nums or k == 0:
# return []
# result = []
# res = [nums[i] for i in range(k - 1)]
# nums = nums[k - 1:]
# for i in nums:
# res.append(i)
# result.append(max(res))
# res.pop(0)
# return result
if not nums or k == 0:
return []
deque = []
# 取出第一个窗口
for i in range(k):
while deque and deque[-1] < nums[i]:
deque.pop()
deque.append(nums[i])
res = [deque[0]]
for i in range(k, len(nums)):
# 确保窗口里面的值不会超出k值
if deque[0] == nums[i - k]:
deque.pop(0)
while deque and deque[-1] < nums[i]:
deque.pop()
deque.append(nums[i])
res.append(deque[0])
return res
两种解法,一种就是遍历nums,通过修改窗口内的值,去找出最大值
第二种通过队列的方式 通过滑动窗口的方式,在队列前面弹出值,在队列后面入队列
里面的解题思路,算法流程以及图都画的很详细