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:
MinStack minStack = new MinStack();minStack.push(-2);minStack.push(0);minStack.push(-3);minStack.getMin(); --> Returns -3.minStack.pop();minStack.top(); --> Returns 0.minStack.getMin(); --> Returns -2.
题意
设计一个栈结构,在实现栈的基础功能之外,还需要实现一个获取当前栈最小值的方法,每个操作的时间复杂度要求为$O(1)$。
思路
维护两个栈来实现输出最小值:一个为普通栈stack,一个用于保存与当前普通栈中元素相对应的最小值栈minStack。push新元素x时,如果当前minStack为空,或者x值小于等于minStack栈顶元素,说明x是加入后普通栈中的最小值,需要在minStack入栈;pop栈顶元素x时,如果x与minStack栈顶元素相同,说明x正是当前普通栈中的最小值,也需要在minStack出栈。
代码实现
class MinStack {private LinkedList<Integer> stack;private LinkedList<Integer> minStack;/** initialize your data structure here. */public MinStack() {stack = new LinkedList<>();minStack = new LinkedList<>();}public void push(int x) {// 注意要使用<=,不然会引发NullPointerExceptionif (minStack.isEmpty() || x <= minStack.peek()) {minStack.push(x);}stack.push(x);}public void pop() {int min = minStack.peek();if (stack.peek() == min) {minStack.pop();}stack.pop();}public int top() {return stack.peek();}public int getMin() {return minStack.peek();}}/*** Your MinStack object will be instantiated and called as such:* MinStack obj = new MinStack();* obj.push(x);* obj.pop();* int param_3 = obj.top();* int param_4 = obj.getMin();*/
