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.
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> Returns -3.
minStack.pop();
minStack.top(); --> Returns 0.
minStack.getMin(); --> Returns -2.
此题为栈的基本操作,加了一个在 O(1) 的时间返回最小值的功能。
具体做法先在初始化的时候定义一个栈。在每次压栈(push)的过程中,先取出最小值(getMin)与当前压入栈的值比较,更新当前最小值。最后,把当前压入值和当前最小值都压入栈中,方便在得到最小值(getMin)的时候直接取出即可。
pop() 之前要确保栈不能为空;top() 是取出栈顶值,而不是删除栈顶元素。
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = [] # 定义一个栈
def push(self, x):
"""
:type x: int
:rtype: void
"""
curMin = self.getMin() # 取出最小值
if curMin == None or x < curMin:
curMin = x
self.stack.append((x, curMin)) # 同时保存最小值
def pop(self):
"""
:rtype: void
"""
if len(self.stack) != 0: # 判断栈是否为空
self.stack.pop()[0]
def top(self):
"""
:rtype: int
"""
if len(self.stack) == 0: # 判断栈是否为空
return None
return self.stack[-1][0]
def getMin(self):
"""
:rtype: int
"""
if len(self.stack) == 0:
return None
return self.stack[-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()
obj = MinStack()
obj.push(-2)
obj.push(1)
obj.push(-3)
print(obj.getMin()) # -3
obj.pop()
print(obj.top()) # 1
print(obj.getMin()) # -2