面试题30:包含min函数的栈
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
minStack.push(INT_MAX); // .push(INI_MAX) 初始化一个最大值
}
void push(int x) {
temp.push(x);
if(x<=minStack.top())
minStack.push(x);
}
void pop() {
if(temp.top() == minStack.top())
minStack.pop();
temp.pop();
}
int top() {
return temp.top();
}
int min() {
return minStack.top();
}
private:
stack<int> temp;
stack<int> minStack;
};