[LeetCode] Min Stack
2015-06-07 01:40
387 查看
The idea is to use two stacks.
For
For
The remaining
The code is as follows.
For
push, the first stack records the pushed elements and the second stack records all the minimum (including duplicates) that have been seen.
For
pop, we need to compare with the top elements of the two stacks. If they are equal (the top element is also minimum, popping it out will change the minimum), pop both; otherwise, only pop the first stack.
The remaining
topand
getMinwill be trivial: just return the top element of the first and second stack respectively.
The code is as follows.
class MinStack { public: void push(int x) { if (stk1.empty() || x <= stk2.top()) stk2.push(x); stk1.push(x); } void pop() { if (stk1.top() == stk2.top()) stk2.pop(); stk1.pop(); } int top() { return stk1.top(); } int getMin() { return stk2.top(); } private: stack<int> stk1; stack<int> stk2; };
相关文章推荐
- About Me
- css ! important 属性详细解释
- ffmpeg的demux流程简析
- Android ViewPager 如何判断当前页面是从前一页还是后一页滑动过来
- Python 中的struct
- 完美解决IE(IE6/IE7/IE8)不兼容HTML5标签的方法
- Struts2中的Action和ActionSupport
- MachineLearning ---- lesson 2 Linear Regression with One Variable
- String运算符重载
- jQuery系列:DOM操作
- 为eclipse离线安装hibernate tools插件
- 直积、直和与张量积简介
- 体验了Sublime + Emmet,才体会到原来前端开发可以这么痛快!
- Java排序算法
- 从把3000行代码重构成15行代码谈起
- [LeetCode] Add and Search Word - Data Structure Design
- spring4+websocket(兼容低版本ie)
- c# webkit 模拟点击
- Looksery Cup 2015 D. Haar Features 暴力
- 2015湘潭邀请赛