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.
Example 1
1 | MinStack minStack = new MinStack(); |
解题思路
在常数时间内获取栈中最小值,需要维护一个 minv
变量,用于保存当前栈的最小值。pop
一个元素时,若该元素等于 minv
,需要更新 minv
。若要在常数时间更新 minv
,需要保存 push(x=minv)
之前栈的最小值,可以在 push(x=minv)
之前先 push
旧的 minv
。这样,在 pop(x=minv)
时,可以利用旧的 minv
更新 minv
。
复杂度分析
- 时间复杂度:$O(1)$
- 空间复杂度:$O(n)$
代码
1 | class MinStack { |