leetcode第155题,这道题是实现一个简单的栈,如果使用python,用list模拟几乎没有什么难度,但是有一些关键性的细节需要注意,这也是这道题考察我们是否能写出一个健壮程序的思想。
- 是否考虑到栈空的一系列情况
- 是否考虑到最小值不存在的情况
- 最小值如何搜索
其中第三个问题很关键,如果单纯调用python中的min函数,会超时,过不了大数据量,我参考的办法是,在压栈的过程中就时刻比较并记录最小值,压栈的内容连着最小值一块压入,这样寻找最小值只需要常数级时间了。
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.s = []
def push(self, x):
"""
:type x: int
:rtype: void
"""
curmin = self.getMin()
if curmin == None or x < curmin:
curmin = x
self.s.append((x,curmin))
def pop(self):
"""
:rtype: void
"""
self.s.pop()
def top(self):
"""
:rtype: int
"""
return self.s[-1][0]
def getMin(self):
"""
:rtype: int
"""
if len(self.s) == 0:
return None
else:
return self.s[-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()