https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof/
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.min(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.min(); --> 返回 -2.
提示:
各函数的调用总次数不超过 20000 次
class MinStack {
Stack<Integer> stack1;
Stack<Integer> stack2;
int minvalue;
/** initialize your data structure here. */
public MinStack() {
//用stack1存当前值
//用stack2存当前的最小值
stack1=new Stack<Integer>();
stack2=new Stack<Integer>();
minvalue=Integer.MAX_VALUE;
}
public void push(int x) {
if(x<minvalue){
minvalue=x;
}
stack1.push(x);
stack2.push(minvalue);
}
public void pop() {
if(!stack1.isEmpty()){
stack1.pop();
stack2.pop();
//注意判断stack2是否为空
if(!stack1.isEmpty()){
minvalue=stack2.peek();
}
else{
minvalue=Integer.MAX_VALUE;
}
}
}
public int top() {
if(!stack1.isEmpty()){
return stack1.peek();
}
else{
return 0;
}
}
public int min() {
return minvalue;
}
}
/**
* 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();
*/