最大栈也是这个思路.
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.stack_min = []
def push(self, x):
"""
:type x: int
:rtype: None
"""
self.stack.append(x)
if len(self.stack_min) == 0 or x <= self.stack_min[-1]:
self.stack_min.append(x)
def pop(self):
"""
:rtype: None
"""
x = self.stack.pop()
if len(self.stack_min) != 0 and self.stack_min[-1] == x:
self.stack_min.pop()
return x
def top(self):
"""
:rtype: int
"""
return self.stack[-1]
def getMin(self):
"""
:rtype: int
"""
return self.stack_min[-1] if len(self.stack_min) != 0 else None