要求设计一个支持push、pop、top和在恒定时间内检索最小元素的堆栈。
push(x)——将元素x推到堆栈顶部;
pop()——删除堆栈顶部的元素;
top()——获取最顶端的元素;
getmin()——检索堆栈中的最小元素。
这道题的关键在于“在恒定时间内检索出最小元素”。
将新添加的数和当前的最小值组成一个元组,加到 list 的最后,在getmin()中只需要返回该元祖的第2个值即可。
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
def push(self, x):
"""
:type x: int
:rtype: void
"""
curMin = self.getMin()
if curMin == None or x < curMin:
curMin = x
self.stack.append((x, curMin))
def pop(self):
"""
:rtype: void
"""
self.stack.pop()
def top(self):
"""
:rtype: int
"""
if not self.stack:
return None
return self.stack[len(self.stack)-1][0]
def getMin(self):
"""
:rtype: int
"""
if not self.stack:
return None
return self.stack[len(self.stack)-1][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()