1、题目描述
设计stack,能返回其中的最小值。
2、思路
用一个数字m记录最小值,每次push都更新最小值,
当pop时,如果栈顶是最小值,则需要更新m;
否则直接弹出栈顶元素。
法2:用另一个stack保存最小值。
pop的时候,如果弹出的是最小值,另一个stack也要跟着弹出。
3、代码
class MinStack {
public:
/** initialize your data structure here. */
stack<int>s;
int m;
MinStack() {
m=INT_MAX;
}
void push(int x) {
s.push(x);
m=min(x,m);
}
void pop() {
if(s.top()==m){
s.pop();
stack<int>s1;
m=INT_MAX;
while(!s.empty()){
int t=s.top();
s.pop();
m=min(t,m);
s1.push(t);
}
while(!s1.empty()){
int t=s1.top();
s1.pop();
s.push(t);
}
}
else s.pop();
}
int top() {
return s.top();
}
int getMin() {
return m;
}
};
class MinStack {
public:
/** initialize your data structure here. */
stack<int>s,s2;
MinStack() {
}
void push(int x) {
s.push(x);
if(s2.empty() || s2.top() >= x)
s2.push(x);
}
void pop() {
int x = s.top();
s.pop();
if(x == s2.top())
s2.pop();
}
int top() {
return s.top();
}
int getMin() {
return s2.top();
}
};