题目:
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- getMin() -- Retrieve the minimum element in the stack.
分析:
python的列表有类似栈的后入先出的增删元素的方式,为了获取当前栈内的最小值,为了时间复杂度最低,可以建立一个最小值栈,在列表添加元素时,同步在最小栈添加当前最小值,弹出元素时同步弹出最小栈最上面的元素,最小栈栈顶始终为当前栈的最小值。
代码:
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.lst = []
self.min = []
def push(self, x):
"""
:type x: int
:rtype: void
"""
self.lst.append(x)
if self.min:
self.min.append(min(x,self.min[-1]))
else:
self.min.append(x)
def pop(self):
"""
:rtype: void
"""
self.lst.pop()
self.min.pop()
def top(self):
"""
:rtype: int
"""
return self.lst[-1]
def getMin(self):
"""
:rtype: int
"""
return self.min[-1]