[LeetCode]Min Stack
来源:互联网 发布:什么叫java参数传递 编辑:程序博客网 时间:2024/05/02 01:58
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- getMin() -- Retrieve the minimum element in the stack.
如何搜索都不可能达到O(1),所以必须在压栈和退栈的过程中维护当前的最小元素
最简单的方法是使用2个栈,一个用来维护当前的元素,一个用来维护当前的最小元素
我们直接可以使用STL的stack来内嵌2个STL栈来实现这个问题,这样我们可以得到如下方案
class MinStack {private: stack<int>_elems; stack<int>_minElems;public: void push(int x) { _elems.push(x); if(_minElems.empty()) _minElems.push(x); else _minElems.push(x > _minElems.top()?_minElems.top():x); } void pop() { _elems.pop(); _minElems.pop(); } int top() { return _elems.top(); } int getMin() { return _minElems.top(); }};
方法可行,问题在于LeetCode对内存有要求,这样维护2个栈,n个元素需要占用2n个空间
可以对第2个做些优化,不需要占用n个元素,当最小元素没有变化时候,不更新minStack,需要修改对应的push和pop实现
void push(int x) { _elems.push(x); if(_minElems.empty()|| x <= _minElems.top()){ _minElems.push(x); } } void pop() { if(_minElems.top() == _elems.top()){ _minElems.pop(); } _elems.pop(); }
0 0
- LeetCode[stack]: Min Stack
- [leetcode][stack] Min Stack
- 【Leetcode】Min Stack
- Leetcode: Min Stack
- leetcode Min stack
- Min Stack -- LeetCode
- Leetcode: Min Stack
- 【LeetCode】Min Stack
- leetcode Min Stack
- leetcode--Min Stack
- [Leetcode]Min stack
- leetcode:Min Stack
- leetcode 之 Min Stack
- leetcode Min Stack
- LeetCode(155) Min Stack
- [LeetCode]Min Stack
- leetcode:Min Stack
- leetcode - Min Stack
- 判断系统是否安装了flash
- 第十二周项目3(2)
- android 2048游戏实现
- 12周。。。银行系统加强版
- HDU 4745 Two Rabbits
- [LeetCode]Min Stack
- 软件工程作业2---小游戏
- 索隆的难题
- iOS分辨率的那些事儿
- leetcode之Linked List Cycle
- 做UIWebView时明白的一些问题
- 用Python开始机器学习(3:数据拟合与广义线性回归)
- 排序算法总结
- 第十二周项目3(4)