题目链接:https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof/
题意:定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
方法: 将
min()
函数复杂度降为 O(1)O(1) 。可借助辅助栈实现
class MinStack {
private:
stack<int> st,st_min;//存储要放入的所有元素,存储最小元素
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
if(!st_min.empty())//假如存储最小元素的栈非空
{
if(x<=st_min.top())
{
st_min.push(x);//x入栈
}
}
else//st_min为空直接入栈
{
st_min.push(x);
}
st.push(x);//该数直接入st的栈
}
void pop() {
if(st.top()==st_min.top()) st_min.pop();//假如st的栈顶元素刚好等于st_min的栈顶元素,st_min栈顶元素出栈
st.pop();//st栈顶元素出栈
}
int top() {
return st.top();
}
int min() {
return st_min.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();
*/