【leetcode】155 - Min Stack
2015-08-08 20:14
295 查看
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.
Solution: 若只维护一个栈stk,在每次getMin的时候检索stk需要两倍的临时空间,倒两次,故用两个栈,一个stk,一个min
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.
Solution: 若只维护一个栈stk,在每次getMin的时候检索stk需要两倍的临时空间,倒两次,故用两个栈,一个stk,一个min
class MinStack { public: void push(int x) { stk.push(x); if(min.empty()||x<=min.top())min.push(x); //if的两个判断条件顺序不能替换,否则stk添加第一个元素后getMin出错 } void pop() { if(stk.top()==min.top()){ stk.pop(); min.pop(); }else stk.pop(); } int top() { return stk.top(); } int getMin() { return min.top(); } private: stack<int> stk; stack<int> min; };
相关文章推荐
- Mysql驱动包版本不一致错误定位
- swift 基础部分
- 20个高级Java面试题汇总
- [leedcode 238] Product of Array Except Self
- 点的双联通+二分图的判定(poj2942)
- 【UML】UML简介
- Java中abstract和final、static
- OC语法——Object-C retain、copy、mutableCopy的详细分析
- Newton's Dark Secrets《牛顿探索》
- poj 2503 Babelfish
- 【机房收费系统】——报表制作
- 深入内存
- Code Forces 37A Towers
- UIViewController的生命周期
- Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream
- UIViewController
- 来自大数据的反思:需要你读懂的10个小故事
- 编写socket通信服务器端程序时的错误解决方法
- 【笔试】4、正整数分解质因数
- 【枚举+贪心】POJ2718-Smallest Difference