- class MinStack {
- //用一个辅助栈存储对应栈元素为栈顶时的最小值
- //当原栈插入一个元素时,辅助栈插入此值与当前辅助栈栈顶的值(即插入前的最小值)的较小值
- Stack
sta1; - Stack
sta2; - public MinStack() {
- sta1 = new Stack
(); - sta2 = new Stack
(); - sta2.push(Integer.MAX_VALUE);
- }
-
- public void push(int val) {
- sta1.push(val);
- sta2.push(Math.min(val, sta2.peek()));
- }
-
- public void pop() {
- sta1.pop();
- sta2.pop();
- }
-
- public int top() {
- return sta1.peek();
- }
-
- public int getMin() {
- return sta2.peek();
- }
- }
-
- /**
- * Your MinStack object will be instantiated and called as such:
- * MinStack obj = new MinStack();
- * obj.push(val);
- * obj.pop();
- * int param_3 = obj.top();
- * int param_4 = obj.getMin();
- */