方法一:队列+双端队列
import queue
class MaxQueue:
def __init__(self):
self.queue = queue.Queue()
self.deque = queue.deque()
def max_value(self) -> int:
return self.deque[0] if self.deque else -1
def push_back(self, value: int) -> None:
while self.deque and self.deque[-1] < value:
self.deque.pop()
self.deque.append(value)
self.queue.put(value)
def pop_front(self) -> int:
if not self.deque:
return -1
ans = self.queue.get()
if ans == self.deque[0]:
self.deque.popleft()
return ans
方法二:队列+数组
import queue
class MaxQueue:
def __init__(self):
self.queue = queue.Queue()
self.stack = []
def max_value(self) -> int:
return self.stack[0] if self.stack else -1
def push_back(self, value: int) -> None:
self.queue.put(value)
while self.stack and self.stack[-1] < value:
self.stack.pop()
self.stack.append(value)
def pop_front(self) -> int:
if not self.stack:
return -1
ans = self.queue.get()
if ans == self.stack[0]:
self.stack.pop(0)
return ans
方法三:数组+数组
class MaxQueue:
def __init__(self):
self.queue = []
self.max_stack = []
def max_value(self) -> int:
return self.max_stack[0] if self.max_stack else -1
def push_back(self, valuea: int) -> None:
self.queue.append(value)
while self.max_stack and self.max_stack[-1] < value:
self.max_stack.pop()
self.max_stack.append(value)
def pop_front(self) -> int:
if not self.queue:
return -1
ans = self.queue.pop(0)
if ans == self.max_stack[0]:
self.max_stack.pop(0)
return ans