我们每次往stack里压入长度为2的数组,第1个元素是需要入栈的整数本身,第2个元素是到目前为止栈内最小的数。
class MinStack {
private Stack<int[]> stack;
/** initialize your data structure here. */
public MinStack() {
stack = new Stack<>();
}
public void push(int x) {
if(stack.isEmpty()){
stack.push(new int[] {x,x});
}else{
stack.push(new int[] {x, Math.min(stack.peek()[1], x)});
}
}
public void pop() {
stack.pop();
}
public int top() {
return stack.peek()[0];
}
public int getMin() {
return stack.peek()[1];
}
}
/**
* 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.getMin();
*/