一 思路
除了min,python的append和pop都能用,为了解决复杂度问题,我们使用辅助栈储存当前最小的数字
二 代码
class MinStack(object):
def __init__(self): """ initialize your data structure here. """ self.stack=[] self._minstack=[]
def push(self, x): """ :type x: int :rtype: None """ self.stack.append(x) if not self._minstack or x<=self._minstack[-1]: self._minstack.append(x)
def pop(self): """ :rtype: None """ if self.stack.pop()==self._minstack[-1]: self._minstack.pop()
def top(self): """ :rtype: int """ return self.stack[-1]
def getMin(self): """ :rtype: int """
return self._minstack[-1]