题目:
请设计一个栈,除了常规栈支持的pop与push函数以外,还支持min函数,该函数返回栈元素中的最小值。执行push、pop和min操作的时间复杂度必须为O(1)。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/min-stack-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class MinStack {
stack<int> s;
stack<int> as;
public:
/** initialize your data structure here. */
MinStack() { //构造函数
as.push(INT_MAX); //为as.top()赋初值,和下面那句的x比较
}
void push(int x) {
s.push(x);
as.push(min(x,as.top())); //和INT_MAX比较了大小
}
void pop() {
s.pop();
as.pop();
}
int top() {
return s.top();
}
int getMin() {
return as.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();
*/