题解 | 包含MIN函数的栈
包含min函数的栈
http://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49
辅助栈关键在于每次都有入栈,入栈元素为最小元素,个数与s保持一致
private:
stack<int> s,minStack;
public:
void push(int value) {
if(minStack.empty()){
minStack.push(value);
}
s.push(value);
if(minStack.empty()){
minStack.push(value);
}
else{
if(minStack.top()>value)
minStack.push(value);
else
minStack.push(minStack.top());//每次让当前栈最小值入栈
}
}
void pop() {
s.pop();
minStack.pop();
}
int top() {
return s.top();
}
int min() {
return minStack.top();
}
};