这题难就难在对空间的限制十分严格。
这个方法是看了Discuss然后自己写的。
注意不要用pair<bool, int>作为一个栈的元素来代替两个栈。
因为,pair<bool, int>的size是4*2,而不是我们认为的4+1。
至于为什么,好像是个值得研究的问题...
class MinStack {
public:
void push(int x) {
if (s.empty()) {
s.push(0);
si.push(false);
m = x;
} else {
long temp = x - m;
if (temp < INT_MIN) s.push(temp - INT_MIN), si.push(true);
else if (temp > INT_MAX) s.push(temp - INT_MAX), si.push(true);
else s.push(temp), si.push(false);
if (x < m) m = x;
}
}
void pop() {
if (s.empty()) return;
long temp = s.top();
if (temp < 0) {
if (si.top()) temp -= INT_MIN;
m = m - temp;
}
s.pop();
si.pop();
}
int top() {
long temp = s.top();
if (temp > 0)
if (si.top()) return temp + m + INT_MAX;
else return temp + m;
else return m;
}
int getMin() {
return m;
}
stack<int> s;
stack<bool> si;
long m;
};