题目:
实现一个带有取最小值min方法的栈,min方法将返回当前栈中的最小值。
你实现的栈将支持push,pop 和 min 操作,所有操作要求都在O(1)时间内完成。
注意事项:
如果堆栈中没有数字则不能进行min方法的调用
##样例:
如下操作:push(1),pop(),push(2),push(3),min(), push(1),min() 返回 1,2,1
这次一编写一个类,想到python中有找最小值的函数,就用python了。
代码:
class MinStack:
l = []
def __init__(self):
# do intialization if necessary
pass
"""
@param: number: An integer
@return: nothing
"""
def push(self, number):
# write your code here
self.l.append(number)
"""
@return: An integer
"""
def pop(self):
# write your code here
return self.l.pop(len(self.l)-1)
"""
@return: An integer
"""
def min(self):
# write your code here
if(self.l):
return min(self.l)
刚开始构造函数中没有加pass,其他地方的l没有加self,导致很多次语法错误,改正之后就一遍过了。