python
class MinStack:
def __init__(self):
self.stack=[]
def push(self, val: int) -> None:
if not self.stack:
self.stack.append([val,val])
else:
self.stack.append([val,min(val,self.stack[-1][1])])
def pop(self) -> None:
self.stack.pop()
def top(self) -> int:
return self.stack[-1][0]
def getMin(self) -> int:
return self.stack[-1][1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
思路:
- 题目要求在常数时间内,所以在
getmin()
函数中使用sort或者min这种弱智的方法 - 我们把每个进入栈的元素定义为
[ val , min ]
,让元素以这种方式入栈,每次只需要维护这个最小值就可以了 - python中用list定义栈的好处是,栈顶元素就是stack[-1]