155. Min Stack
2016-04-25 09:09
260 查看
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.
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.
class MinStack { // stack: store the stack numbers private Stack<Integer> stack = new Stack<Integer>(); // minStack: store the current min values private Stack<Integer> minStack = new Stack<Integer>(); public void push(int x) { // store current min value into minStack if (minStack.isEmpty() || x <= minStack.peek()) minStack.push(x); stack.push(x); } public void pop() { // use equals to compare the value of two object, if equal, pop both of them if (stack.peek().equals(minStack.peek())) minStack.pop(); stack.pop(); } public int top() { return stack.peek(); } public int getMin() { return minStack.peek(); } }
相关文章推荐
- 设计模式读书笔记之命令模式(Command Pattern)
- 新名词,要了解的
- 数据库ACID
- Linux下php安装Redis扩展
- C++ Java要点记录
- 设计模式读书笔记之职责链模式(chain of responsibility)
- 有关于我的一点想法
- 053(四十七)
- python学习的几篇文章推荐
- 将二进制数据嵌入 XML 文档的三种方法
- 169. Majority Element
- 设计模式读书笔记之中介者模式(mediator pattern)
- 设计模式读书笔记之享元模式(Flyweight pattern)
- LintCode: Fizz Buzz
- 如何设计好词袋模型BoW模型的类类型
- win7 64位4GB内存下 tomcat7扩大内存
- 第三届百草味517吃货节即将盛大开启,跨界合作成为最大亮点
- NBUT 1462 台球碰撞 几何基础 思维
- 设计模式读书笔记之解释器模式(Interpreter pattern)
- HttpWebRequest的GetResponse或GetRequestStream偶尔超时 + 总结各种超时死掉的可能和相应的解决办法