方法一:辅助栈
class MinStack:
def __init__(self):
self.stack = []
self.min_stack = [] #降序
def push(self, x: int) -> None:
self.stack.append(x)
if not self.min_stack or x <= self.min_stack[-1] : #如果加进来的元素更小
self.min_stack.append(x)
def pop(self) -> None:
a = self.stack.pop()
if a == 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] #代表栈的最小值