解题思路
每次如果当前值比最小值还要小,则将第二小的值入栈,这样即使最小值出栈后也有最小值信息
代码
class MinStack {int min = Integer.MAX_VALUE;Stack<Integer> stack = new Stack<Integer>();public void push(int x) {// only push the old minimum value when the current// minimum value changes after pushing the new value xif(x <= min){stack.push(min);min=x;}stack.push(x);}public void pop() {// if pop operation could result in the changing of the current minimum value,// pop twice and change the current minimum value to the last minimum value.if(stack.pop() == min) min=stack.pop();}public int top() {return stack.peek();}public int getMin() {return min;}}
