题目描述:
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
链接:https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof/
该题主要是在调用min函数时,可以得到栈中的最小值。
- 借用一个辅助栈
- 辅助栈为空时,直接放入元素,辅助栈不为空时,若出栈的元素和辅助栈栈顶元素相等,则辅助栈和栈同时出栈
- 入栈时,入栈元素与辅助栈栈顶相等时,则辅助栈需要将该元素入栈
代码:
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {}
void push(int x) {
_st.push(x);//该栈直接放入数据
if(_minst.empty() || x <= _minst.top())//辅助栈为空或者小于等于栈顶元素时,入栈
_minst.push(x);
}
void pop() {
if(_st.top() == _minst.top())//出栈
_minst.pop();
_st.pop();
}
int top() {
return _st.top();//栈顶元素
}
int min() {
return _minst.top();//min函数,获取栈中最小值
}
private:
stack<int> _st;//栈
stack<int> _minst;//辅助栈
};