双栈解法
class MinStack {
private:
stack<int> s1;
stack<int> s2;
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
s1.push(x);
if(s2.empty() || x <= s2.top()) //s2为空 一定是小于等于号 因为可能会重复 pop会出问题
s2.push(x);
}
void pop() {
if(s1.top() == s2.top())
s2.pop();
s1.pop();
}
int top() {
return s1.top();
}
int getMin() {
return s2.top();
}
};
单栈解法
思路主要是存储一个pair结构,first代表当前压入的值,second代表当前的最小值。
class MinStack {
private:
stack<pair<int,int>> s1;
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
if(s1.empty())
s1.push(make_pair(x,x));
else
{
s1.push(make_pair(x,min(x,s1.top().second)));
}
}
void pop() {
s1.pop();
}
int top() {
return s1.top().first;
}
int getMin() {
return s1.top().second;
}
};