任务
设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
- push(x) – 将元素 x 推入栈中。
- pop() – 删除栈顶的元素。
- top() – 获取栈顶元素。
- getMin() – 检索栈中的最小元素。
代码
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.min = None
def push(self, x: int) -> None:
self.stack.append(x)
if self.min == None or self.min > x:
self.min = x
def pop(self) -> None:
pop = self.stack.pop()
if len(self.stack) == 0:
self.min = None
if pop == self.min:
self.min = self.stack[0]
for i in self.stack:
if i < self.min:
self.min = i
def top(self) -> int:
return self.stack[-1]
def getMin(self) -> int:
return self.min