import math
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.l = list()
self.MIN = [math.inf]#利用双栈
def push(self, x: int) -> None:
if x <= self.MIN[-1]:
self.MIN.append(x)
self.l.append(x)
def pop(self) -> None:
if len(self.l):
if self.l.pop() == self.MIN[-1]:
self.MIN.pop()
def top(self) -> int:
if len(self.l):
return self.l[-1]
else:
return None
def getMin(self) -> int:
if len(self.MIN) == 1:
return None
else:
return self.MIN[-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()
思路就是利用双栈来实现快速查找最小值
一些小技巧:在python中常用pop push方法来进行栈操作,
pop方法还返回被弹出的值,因此可以直接把被弹出的值与存放最小值的栈中的值进行比较