雙棧解法
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;
}
};