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.
Example:
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.
#### 方法
這題不支持c台妆,于是用python來實現(xiàn)秕噪。
注意不能用一個變量來記錄stack的最小值斤斧,因為stack會被pop(),最小值可能會被取走谣拣,因此用了```self.mins```這個list來保存最小值,min[i]表示i個數(shù)的最小值族展。
#### python代碼
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.mins = []
def push(self, x):
"""
:type x: int
:rtype: void
"""
min_val = self.getMin()
if min_val==None or min_val>x:
min_val = x
self.mins.append(min_val)
self.stack.append(x)
def pop(self):
"""
:rtype: void
"""
self.mins.pop()
return self.stack.pop()
def top(self):
"""
:rtype: void
"""
return self.stack[-1]
def getMin(self):
"""
:rtype: void
"""
if len(self.mins) == 0:
return None
return self.mins[-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()
minStack = MinStack()
minStack.push(-2)
minStack.push(0)
minStack.push(-3)
assert minStack.getMin()==-3
assert minStack.pop()==-3
assert minStack.top()==0
assert minStack.getMin()==-2