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.
Solution in C++:
class MinStack {
public:
vector<int> stack;
int min;
MinStack(){
min = INT_MAX;
}
void push(int x) {
stack.push_back(x);
if(x<min) min=x;
}
void pop() {
int dele;
if(stack.size()>0){
dele = stack[stack.size()-1];
stack.pop_back();
}
if(dele==min){
min = INT_MAX;
for(int i=0; i<stack.size(); i++)
min=min<=stack[i]?min:stack[i];
}
}
int top() {
return stack[stack.size()-1];
}
int getMin() {
return min;
}
};