How would you design a stack which, in addition to push and pop, has a function min which returns the minimum element? Push, pop and min should all operate in 0(1) time.
class MinStack {
public:
/** initialize your data structure here. */
stack<int> s;
int min = INT_MAX;
MinStack() {
}
void push(int x) {
if (x <= min) {
s.push(min);
min = x;
}
s.push(x);
}
void pop() {
int cur = s.top(); s.pop();
if (cur == min) {
min = s.top(); s.pop();
}
}
int top() {
return s.top();
}
int getMin() {
return min;
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(x);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/
two stack
class MinStack {
public:
/** initialize your data structure here. */
stack<int> s, min;
MinStack() {
min.push(INT_MAX);
}
void push(int x) {
if (x <= min.top()) {
min.push(x);
}
s.push(x);
}
void pop() {
if (s.top() == min.top()) {
min.pop();
}
s.pop();
}
int top() {
return s.top();
}
int getMin() {
return min.top();
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(x);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/