【题目描述】
【思路】
使用单调栈(minstack)维系原基础栈(data)的最小值。原栈栈顶数值只有大于单调栈的栈顶元素才push进单调栈。
class MinStack {
/** initialize your data structure here. */
/*
两个栈 data基础栈存放原数据 minstack最小栈存放最小值
*/
Stack<Integer> data;
Stack<Integer> minstack;
public MinStack() {
data = new Stack<Integer>();
minstack = new Stack<Integer>();
}
public void push(int x) {
if( data.empty() ){
data.push(x);
minstack.push(x);
//要return
return;
}
int min = minstack.peek();
if(x > min) minstack.push(min);
else minstack.push(x);
data.push(x);
}
public void pop() {
minstack.pop();
data.pop();
}
public int top() {
return data.peek();
}
public int getMin() {
return minstack.peek();
}
}
/**
* 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();
*/