题解如代码,需要使用一个辅助栈,用来存当前最小值:
import java.util.Stack; public class Solution { Stack<Integer> stack = new Stack<>(); //需要一个辅助栈来存放最小元素,该辅助栈栈顶则为当前最小元素 Stack<Integer> minStack = new Stack<>(); int min = Integer.MAX_VALUE; public void push(int node) { if(node < min) { minStack.push(node); min = node; } stack.push(node); } public void pop() { int t = stack.pop(); //判断stack pop的元素是否是当前最小值,是的话需要都pop if(t == min && minStack.size() != 0){ minStack.pop(); } } public int top() { return stack.peek(); } public int min() { return minStack.peek(); } }