劍指Offer-30 包含min函式的棧
阿新 • • 發佈:2018-12-10
題目:
設計一個支援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()