Min Stack
2015-08-03 17:18
309 查看
</pre><p style="margin-top:0px; margin-bottom:10px; color:rgb(51,51,51); font-family:'Helvetica Neue',Helvetica,Arial,sans-serif; font-size:14px; line-height:30px">Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.</p><ul style="margin-top:0px; margin-bottom:10px; color:rgb(51,51,51); font-family:'Helvetica Neue',Helvetica,Arial,sans-serif; font-size:14px; line-height:30px"><li style="">push(x) -- Push element x onto stack.</li><li style="">pop() -- Removes the element on top of the stack.</li><li style="">top() -- Get the top element.</li><li style="">getMin() -- Retrieve the minimum element in the stack.</li></ul><p></p><p>思路:关键点在于获取最小值,一般的方法就是遍历整个容器,除非容器是有序的;但是栈本身无法实现在不影响他本身的情况下遍历,除非不断抛出最上方的元素,所以需要有一个额外的容器来存储每次栈中的元素,然后遍历他来找到最小值。</p><p></p><p><pre name="code" class="java">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; } }
相关文章推荐
- Install Scala and SBT using apt-get on Ubuntu 14.04 or any Debian derivative using apt-get
- jQuery 效果 - slideToggle() 方法
- distribute_crawler项目实战
- 实习第3天 版本控制 repeater中服务器控件无法调用
- 如何在内核里面查找某些结构体或者宏的定义
- 图标抖动
- 使用 Salt + Hash 来为密码加密
- Qt容器类整理
- 【Android应用开发技术:用户界面】章节列表
- Unity3D NGUI 点击穿透问题的解决方案
- 学习笔记——Java内部类练习题
- shell 二元操作符 =~
- 实习第2天 环境配置 vs2010 64位系统下连接oracle的问题
- 转VS2010解决方案转换到VS2008
- fedora下安装apache过程实录
- Win10电脑桌面搜索栏如何隐藏/关闭?
- 值传递、指针传递和引用传递的区别
- 推荐4个Android引导页控件
- Spring 之八 整合Mybatis
- Apache优化:修改最大并发连接数