使用辅助栈存储栈的数据栈最小值,数据栈入栈出栈的时候,辅助栈要对应入栈出栈。
Java的Interger比较,不要使用"=="。
class MinStack {
Deque<Integer> data;
Deque<Integer> helper;
public MinStack() {
data = new LinkedList<>();
helper = new LinkedList<>();
helper.push(Integer.MAX_VALUE);
}
public void push(int val) {
data.push(val);
if(val <= helper.peek()) {
helper.push(val);
}
}
public void pop() {
if(data.peek().equals(helper.peek())) {
helper.pop();
}
data.pop();
}
public int top() {
return data.peek();
}
public int getMin() {
return helper.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();
*/