使用辅助栈 时间复杂度 O(1)
非同步栈
class MinStack:
def __init__(self):
self.stack = []
self.min_stack = []
def push(self, val: int) -> None:
self.stack.append(val)
if not self.min_stack or val <= self.min_stack[-1]:
self.min_stack.append(val)
def pop(self) -> None:
if self.stack.pop() == self.min_stack[-1]:
self.min_stack.pop()
def top(self) -> int:
return self.stack[-1]
def getMin(self) -> int:
return self.min_stack[-1]
同步栈
class MinStack:
def __init__(self):
self.stack = []
# 添加正无穷 这样第一次添加 不用判断边界
self.min_stack = [math.inf]
def push(self, val: int) -> None:
self.stack.append(val)
self.min_stack.append(min(self.min_stack[-1], val))
def pop(self) -> None:
self.stack.pop()
self.min_stack.pop()
def top(self) -> int:
return self.stack[-1]
def getMin(self) -> int:
return self.min_stack[-1]