思路:使用两个栈,栈A,栈B,栈A用于存储正常的值,栈B存储最小的元素,插入时,栈A直接插入元素到栈顶,栈B先判断是否为空,空的话直接插入,若插入元素小于栈顶元素,也同样插入。弹出时若弹出的元素与栈B的栈顶元素相同,则栈B也弹出。
具体代码如下:
class MinStack {
Stack<Integer> A;
Stack<Integer> B;
/** initialize your data structure here. */
public MinStack() {
A=new Stack<>();
B=new Stack<>();
}
public void push(int x) {
A.push(x);
if(B.empty()||B.peek()>=x) B.push(x);
}
public void pop() {
if(A.pop().equals(B.peek())) B.pop();
}
public int top() {
return A.peek();
}
public int min() {
return B.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.min();
*/