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.
(设计一个堆栈类,并可以O(1)定位到最小值)
Example:
1. 牺牲空间复杂度来实现时间复杂度
为了能够快速在动态出栈,入栈的过程中得到当前堆栈的最小值,我们需要维护一个与当前栈相同大小的“最小栈”,并在入栈的时候更新一致,具体实现过程如下:
1 | class MinStack: |