Min Stack
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.
建立一个辅助栈,存储当前的最小值。
running time: O(n)
space: O(n)
class MinStack:
# @param x, an integer
# @return an integer
def __init__(self):
self.s = []
self.hs = [] #create a help stack.
def push(self, x):
if len(self.s) == 0 or x <= self.hs[-1]:
self.hs.append(x)
self.s.append(x)
# @return nothing
def pop(self):
if self.s[-1] == self.hs[-1]:
self.hs.pop()
self.s.pop()
# @return an integer
def top(self):
if len(self.s) != 0:
return self.s[-1]
# @return an integer
def getMin(self):
if len(self.hs) != 0:
return self.hs[-1]