题目:
设计一个支持push,pop,top等操作并且可以在O(1)时间内检索出最小元素的堆栈。
解答:
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.data = []
self.minValue = []
def push(self, x):
"""
:type x: int
:rtype: void
"""
if not self.data:
self.data.append(x)
self.minValue.append(x)
else:
self.data.append(x)
top = self.minValue[-1]
if x < top:
self.minValue.append(x)
else:
self.minValue.append(top)
def pop(self):
"""
:rtype: void
"""
if self.data:
self.minValue.pop()
return self.data.pop()
def top(self):
"""
:rtype: int
"""
if self.data:
return self.data[-1]
def getMin(self):
"""
:rtype: int
"""
if self.minValue:
return self.minValue[-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()