已解答
中等
相关标签
相关企业
提示
设计一个支持 push
,pop
,top
操作,并能在常数时间内检索到最小元素的栈。
实现 MinStack
类:
MinStack()
初始化堆栈对象。void push(int val)
将元素val推入堆栈。void pop()
删除堆栈顶部的元素。int top()
获取堆栈顶部的元素。int getMin()
获取堆栈中的最小元素。
class MinStack(object):
def __init__(self):
self.stack=[]
self.minStack=[]
def push(self, val):
"""
:type val: int
:rtype: None
"""
self.stack.append(val)
if self.minStack==[]:
self.minStack.append(val)
else:
self.minStack.append(min(val,self.minStack[-1]))
def pop(self):
"""
:rtype: None
"""
self.stack.pop()
self.minStack.pop()
def top(self):
"""
:rtype: int
"""
return self.stack[-1]
def getMin(self):
"""
:rtype: int
"""
return self.minStack[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()