*155-最小栈
题目
要求
设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) -- 将元素 x 推入栈中。
pop() -- 删除栈顶的元素。
top() -- 获取栈顶元素。
getMin() -- 检索栈中的最小元素。
思路
使用两个栈, 一个作为正常的栈进行操作, 另一个存储最小值, 栈顶元素就是当前栈中所有元素的最小值. 如果当前入栈的元素不比当前最小栈的栈顶元素大(考虑到元素重复), 就压入到最小栈中.
最大栈也是这个思路.
代码
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.stack_min = []
def push(self, x):
"""
:type x: int
:rtype: None
"""
self.stack.append(x)
if len(self.stack_min) == 0 or x <= self.stack_min[-1]:
self.stack_min.append(x)
def pop(self):
"""
:rtype: None
"""
x = self.stack.pop()
if len(self.stack_min) != 0 and self.stack_min[-1] == x:
self.stack_min.pop()
return x
def top(self):
"""
:rtype: int
"""
return self.stack[-1]
def getMin(self):
"""
:rtype: int
"""
return self.stack_min[-1] if len(self.stack_min) != 0 else None
最后更新于
这有帮助吗?