Problem
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.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/min-stack
Method One
利用辅助栈存储每种情况的最小值。
class MinStack {
stack<int> q1,q2;
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
q1.push(x);
if (q2.empty()||x < getMin()) q2.push(x);
else q2.push(getMin());
}
void pop() {
q1.pop();
q2.pop();
}
int top() {
return q1.top();
}
int getMin() {
return q2.top();
}
};