Min Stack
Question
- leetcode155
- lintcode: (12) Min Stack
Implement a stack with min() function,
which will return the smallest number in the stack.
It should support push, pop and min operation all in O(1) cost.
Example
Operations: push(1), pop(), push(2), push(3), min(), push(1), min() Return: 1, 2, 1
Note
min operation will never be called if there is no number in the stack
题解
『最小』栈,要求在栈的基础上实现可以在 $$O(1)$$ 的时间内找出最小值,一般这种 $$O(1)$$的实现往往就是哈希表或者哈希表的变体,这里简单起见可以另外克隆一个栈用以跟踪当前栈的最小值。
class MinStack(object):
def __init__(self):
# do some intialize if necessary
self.stack = []
self.minstack = []
def push(self, number):
# write yout code here
self.stack.append(number)
if len(self.minstack) == 0 or number <= self.minstack[-1]:
self.minstack.append(number)
def pop(self):
# pop and return the top item in stack
if self.stack[-1] == self.minstack[-1]:
self.minstack.pop()
return self.stack.pop()
def min(self):
# return the minimum number in stack
return self.minstack[-1]
源码分析
取最小栈的栈顶值时需要先判断是否为空栈(而不仅是 null)。
复杂度分析
均为 $$O(1)$$.