【题目】
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- getMin() -- Retrieve the minimum element in the stack.
【思路】
题目要求能在常数时间检索出最小值,可以考虑使用两个stack实现,一个stack用于正常的push、pop、top,另一个用于存放最小值。
【代码】
class MinStack {
public:
void push(int x) {
st.push(x);
if(stMin.empty() || x<=stMin.top()){
stMin.push(x);
}
}
void pop() {
int a=st.top();
st.pop();
if(a==stMin.top()){
stMin.pop();
}
}
int top() {
return st.top();
}
int getMin() {
return stMin.top();
}
private:
stack<int> st;
stack<int> stMin;
};