问题描述:
请设计一个栈,除了常规栈支持的pop与push函数以外,还支持min函数,该函数返回栈元素中的最小值。执行push、pop和min操作的时间复杂度必须为O(1)。
示例:
MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); --> 返回 -3. minStack.pop(); minStack.top(); --> 返回 0. minStack.getMin(); --> 返回 -2.
解决方案:
1、设计一个栈,即可套用栈的模板
2、额外增加返回最小值 min()函数的功能
==> 问题转化:利用栈,求最小值,且不改变原来的栈
3、利用辅助栈实现:辅助栈中依次存储当前的最小值,使用getMin()函数取出
函数代码:
class MinStack { stack<int> x; stack<int> min_stack; public: MinStack() { min_stack.push(99999); } void push(int x) { x.push(x); min_stack.push( min(min_stack.top(), x) ); } void pop() { x.pop(); min_stack.pop(); } int top() { return x.top(); } int getMin() { return min_stack.top(); } };