题目概述
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(); |
本题的解法就是要实现两个栈。其中一个栈用来存放原数据信息,第二个栈用来存放当前栈的最小值。第二个栈的栈顶是当前栈的最小值。在进行push和pop的时候,对第一个栈进行常规操作,当push的值小于第二个栈的栈顶时,要将该值也push进第二个栈;如果pop出的值为第二个栈的栈顶元素时,也需要对第二个栈进行pop操作。
代码实现
1 | class MinStack { |