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.
Answer:
method 1:
class MinStack {
stack<int> stk;
int min = -1;
public:
void push(int x) {
if(stk.empty()){
stk.push(0);
min = x;
}
else{
stk.push(x-min);
if(x<min){
min = x;
}
}
}
void pop() {
if(!stk.empty()){
if(stk.top()<0){
min = min - stk.top();
}
stk.pop();
}
}
int top() {
return stk.top() + min;
}
int getMin() {
return min;
}
};
No comments:
Post a Comment