DAY2. 包含min函数的栈
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
/*
思路:可以加上一个辅助栈,用来显示主栈中每一位的最小值
A栈push(a),如果此时a小于B.top(),那么就B.push(a),反之,将B.push(B.top())
在下面的代码中,我觉得如果题目一开始就查询min(),会返回INT_MAX,与题意不符,但是Leetcode过了
*/
class MinStack {
stack<int> A;
stack<int> B;//辅助栈
public:
/** initialize your data structure here. */
MinStack() {
B.push(INT_MAX);
}
void push(int x) {
A.push(x);
if(x<B.top())
B.push(x);
else
B.push(B.top());
}
void pop() {
A.pop();
B.pop();
}
int top() {
return A.top();
}
int min() {
return B.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->min();
*/