Min Stack
2015-08-03 17:23
363 查看
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<Integer> stack=new Stack<>(); List<Integer> list=new ArrayList<>(); public void push(int x) { stack.push(x); list.add(x); } public void pop() { stack.pop(); list.remove(list.size()-1); } public int top() { return stack.peek(); } public int getMin() { int min=list.get(0); //注意将最小值设为第一位 for(int i=0;i<list.size();i++){ if(min>list.get(i)) min=list.get(i); } return min; } }
相关文章推荐
- notes
- Linux进程控制相关概念
- Modernizr的介绍和使用
- NSURL
- 程序员学炒股(2) 个股和大盘的关系
- Ubuntu 14.04最小安装之后要做的事
- Composite模式 组合模式
- Java实现“年-月-日 上午/下午时:分:秒”的简单代码
- android自定义控件(一) 官方文档的翻译
- Halcon学习笔记_01:Threshold
- Runtime学习1
- 原生JS 封装运动函数
- Eclipse注解模板设置
- 前端的Project示例
- POJ 1026 - Cipher【置换群】
- 实习第6天 Oracle执行计划 联想超级本只能重装win8
- 未能创建SSL/TLS安全通道,导致的通过HTTPS协议访问WCF服务
- android:persistentDrawingCache含义
- wireshark抓包图解 TCP三次握手/四次挥手详解
- 百度导航