1.辅助栈
建立一个辅助栈,对于当前元素x,另一个栈保持与之对应的截止到当前的最小元素,
将辅助栈的栈顶元素与当前元素x比较,若x>s2.top,则s2入栈s2.top(),否则入栈x
举例如下:设栈s1,s2
入栈顺序为-2 0 -3 2 -4
s1的值为-2 0 -3 2 -4
s2的值为-2 -2 -3 -3 -4
代码如下:
class MinStack {
stack<int> st;
stack<int> minst;
public:
/** initialize your data structure here. */
MinStack() {
//设置辅助栈,对于每一个x入栈,再另一个栈中与其对应的插入的都是当前最小元素
//st=new stack<>();
//minst=new stack<>();
}
void push(int x) {
st.push(x);
if(!minst.empty()&&minst.top()<x)
minst.push(minst.top());
else
minst.push(x);
}
void pop() {
st.pop();
minst.pop();
}
int top() {
return st.top();
}
int min() {
return minst.top();
}
};
/**
* 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();
*/