剑指 Offer 59 - II. 队列的最大值

Difficulty
Medium
Tags
单调队列
URL
https://leetcode.cn/problems/dui-lie-de-zui-da-zhi-lcof/
Star
请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_valuepush_backpop_front均摊时间复杂度都是O(1)。
若队列为空,pop_frontmax_value 需要返回 -1
示例 1:
输入: ["MaxQueue","push_back","push_back","max_value","pop_front","max_value"] [[],[1],[2],[],[],[]] 输出:[null,null,null,2,1,2]
示例 2:
输入: ["MaxQueue","pop_front","max_value"] [[],[],[]] 输出:[null,-1,-1]
限制:
  • 1 <= push_back,pop_front,max_value的总操作数 <= 10000
  • 1 <= value <= 10^5

法1 单调队列设计题

思路
参考 单调栈的设计题,思想是类似的。
本题使用两个队列,
队列1 为普通队列,正常右近左出。
队列2 为单调队列,队首存放的是最大值。然后当队列1 弹出的数字等于当前队首时,当前堆首也要出队。当队列1进来的数字更大时,需要立马更新单调队列。
题解
class MaxQueue: def __init__(self): self.queue_1 = deque() self.queue_2 = deque() def max_value(self) -> int: if len(self.queue_2) == 0: return -1 return self.queue_2[0] def push_back(self, value: int) -> None: self.queue_1.append(value) while len(self.queue_2) > 0 and value > self.queue_2[-1]: self.queue_2.pop() self.queue_2.append(value) def pop_front(self) -> int: if len(self.queue_1) == 0: return -1 res = self.queue_1.popleft() if res == self.max_value(): self.queue_2.popleft() return res # 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()