Description
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 | MinStack minStack = new MinStack(); |
解法
用两个栈来实现,其中一个栈正常地存数,另一个存对饮栈状态第一个栈中的最小值即可。
具体代码如下:
1 | class MinStack { |