- 主要是在添加函数的位置要注意判断一下B栈的peek元素,及时更新最小值
- pop 位置也要考虑是否操作B栈的peek元素
class MinStack {
Stack<Integer> A, B;
/** initialize your data structure here. */
public MinStack() {
A = new Stack<>();
B = new Stack<>();
}
public void push(int x) {
A.add(x);
// if(B.isEmpty() || B.peek() >= x)
if(B.empty() || B.peek() >= x)
B.add(x);
}
public void pop() {
if(A.pop().equals(B.peek()))
B.pop();
}
public int top() {
return A.peek();
}
public int min() {
return B.peek();
}
}