方法一: 建议使用该方法
class MinStack:
def __init__(self):
self.stack = []
self.aux_stack = []
def push(self, x: int) -> None:
self.stack.append(x)
if not self.aux_stack or self.aux_stack[-1] >= x:
self.aux_stack.append(x)
def pop(self) -> None:
if self.stack.pop() == self.aux_stack[-1]:
self.aux_stack.pop()
def top(self) -> int:
if self.stack:
return self.stack[-1]
return None
def min(self) -> int:
if self.stack:
return self.aux_stack[-1]
return None
方法二: 每次入栈将一个元祖入栈,Tuple(当前元素,当前栈中元素的最小值)
class MinStack:
def __init__(self):
self.stack = []
def push(self, x: int) -> None:
if not self.stack or self.stack[-1][1] >= x:
self.stack.append((x, x)) # 元祖的第一个值为入栈的元素本身,第二个值为当前栈中最小元素
else:
self.stack.append((x, self.stack[-1][1]))
def pop(self) -> None:
if self.stack:
self.stack.pop()
return None
def top(self) -> int:
if self.stack:
return self.stack[-1][0]
return None
def min(self) -> int:
if self.stack:
return self.stack[-1][1]
return None