20、包含min函数的栈
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.min(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.min(); --> 返回 -2.
提示:
各函数的调用总次数不超过 20000 次
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof
思路:
我们新建两个栈,栈1存原数据,栈2存最小值。每次当我们插入数据的时候,栈1直接插入元素,栈2的时候,我们只需要比较一下栈2的栈头,如果当前元素比栈头小,那么我们就将这个元素插入到栈2,如果大于,那么我们就将栈2的栈头再插入一遍栈2即可。
图解:
代码:
class MinStack {
public:
/** initialize your data structure here. */
stack<int> stk1, stk2 ; //stk1是存的原数据,stk2存的是最小值数据
MinStack() {
}
void push(int x) {
//同步插入
stk1.push(x);
if(stk2.size()) x = stk2.top() > x ? x: stk2.top(); //比较当前元素和栈2的栈头
stk2.push(x);
}
void pop() {
//同步删除
stk1.pop();
stk2.pop();
}
int top() {
return stk1.top(); //原栈
}
int min() {
return stk2.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();
*/