设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
- push(x) —— 将元素 x 推入栈中。
- pop() —— 删除栈顶的元素。
- top() —— 获取栈顶元素。
- getMin() —— 检索栈中的最小元素。
- pop、top 和 getMin 操作总是在 非空栈 上调用。
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = list()
self.min = None
def push(self, x: int) -> None:
if self.min is None:
self.min = x
else:
self.min = min(self.min, x)
self.stack.append(x)
def pop(self) -> None:
self.stack.pop()
if self.stack:
self.min = min(self.stack)
else:
self.min = None
def top(self) -> int:
return self.stack[-1]
def getMin(self) -> int:
return self.min