解法一
辅助栈法,维护最小值 。
public:
/** initialize your data structure here. */
stack<int> st,stHelp;
MinStack() {
}
void push(int x) {
st.push(x);
if(stHelp.empty())stHelp.push(x);
else if(x<stHelp.top()) stHelp.push(x);
else stHelp.push(stHelp.top());
}
void pop() {
st.pop();
stHelp.pop();
}
int top() {
return st.top();
}
int min() {
return stHelp.top();
}
};
解法二(优化掉辅助栈空间)
主栈保存原始数据与min的差值,维护一个最小值变量。(压栈和弹栈时维护)
public:
/** initialize your data structure here. */
stack<long long> st_diff; //long long 防溢出
long long minV = INT_MAX;
MinStack() {}
void push(int x) {
st_diff.push(x-minV);
if(x-minV<0) minV = x;
}
void pop() {
long long y = st_diff.top();
if(y<0) minV = minV - y; //恢复前一个min值
st_diff.pop();
}
int top() {
long long y = st_diff.top();
if(y<0) return minV;
else return minV + y;
}
int min() {
return minV;
}
};
代码较简单,看不懂的,对着代码推导一下就好。