原題
實現一個帶有取最小值min方法的棧,min方法將返回當前棧中的最小值。你實現的棧將支持push,pop和min操作,所有操作要求都在O(1)時間內完成。
解題思路
- 使用兩個stack實現, 一個stack正常存儲數值,另一個stack存儲每次的最小值(保存最小值的變化序列)
完整代碼
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.minstack = []
self.stack = []
def push(self, x):
"""
:type x: int
:rtype: nothing
"""
self.stack.append(x)
if len(self.minstack) == 0 or self.minstack[-1] > x:
self.minstack.append(x)
else:
self.minstack.append(self.minstack[-1])
def pop(self):
"""
:rtype: nothing
"""
self.minstack.pop()
return self.stack.pop()
def top(self):
"""
:rtype: int
"""
return self.stack[-1]
def getMin(self):
"""
:rtype: int
"""
return self.minstack[-1]