考虑双栈
一个存储数据
一个存储每个位置的最小值
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.val_stack = []
self.min_stack = []
def push(self, x: int) -> None:
self.val_stack.append(x)
if self.min_stack != []:
self.min_stack.append(min(self.min_stack[-1],x))
else:
self.min_stack.append(x)
def pop(self) -> None:
self.min_stack.pop(-1)
return self.val_stack.pop(-1)
def top(self) -> int:
return self.val_stack[-1]
def getMin(self) -> int:
return self.min_stack[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()