要点:存储最小值--双栈存储,最小值栈只存入不比头元素大的。出栈时进行比较,存在相同的元素时,最小值栈才出栈。
public class MinStack {
/** initialize your data structure here. */
Stack<Integer> stk;
Stack<Integer> Min;
public MinStack() {
stk = new Stack<Integer>();
Min = new Stack<Integer>();
}
public void push(int x) {
if (Min.isEmpty()){
Min.push(x);
}else if(x<=Min.peek()){
Min.push(x);
}
stk.push(x);
}
public void pop() {
if(Min.peek().equals(stk.pop())){
Min.pop();
}
}
public int top() {
return stk.peek();
}
public int min() {
return Min.peek();
}
}