From : https://leetcode.com/problems/min-stack/
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.
class MinStack {
stack<int> nums;
stack<int> mins;
public:
void push(int x) {
nums.push(x);
if(mins.empty() || mins.top() >= x) mins.push(x);
}
void pop() {
if(!nums.empty()) {
int top = nums.top();
nums.pop();
if(!mins.empty()) if(top == mins.top()) mins.pop();
}
}
int top() {
return nums.top();
}
int getMin() {
if(!mins.empty()) return mins.top();
return 0;
}
};