Min Stack
2016-07-09 07:59
190 查看
Implementastackwithmin()function,whichwillreturnthesmallestnumberinthestack.
Itshouldsupportpush,popandminoperationallinO(1)cost.
Notice
minoperationwillneverbecalledifthereisnonumberinthestack.
Example
Itshouldsupportpush,popandminoperationallinO(1)cost.
Notice
minoperationwillneverbecalledifthereisnonumberinthestack.
Example
push(1) pop()//return1 push(2) push(3) min()//return2 push(1) min()//return1 分析: 用另一个stack来保存当前最小的值。
publicclassMinStack{ Stack<Integer>elements=newStack<Integer>(); Stack<Integer>minStack=newStack<Integer>(); publicMinStack(){ //doinitializeifnecessary } publicvoidpush(intx){ elements.push(x); if(minStack.isEmpty()||x<=minStack.peek()){ minStack.push(x); } } publicintpop(){ if(elements.isEmpty()){ return-1; } //这个地方太蛋疼了,居然要用equals... if(elements.peek().equals(minStack.peek())){ minStack.pop(); } returnelements.pop(); } publicintmin(){ returnminStack.peek(); } }
相关文章推荐
- 简单排序
- 2043. 【2016.5.21普及组模拟】约数国王(A king)
- FrameLayout(帧布局)
- sql中where 1=1和 0=1 的作用
- 2042. 【2016.5.21普及组模拟】SuperPow
- 【NOI2002】银河英雄说
- 2041. 【2016.5.21普及组模拟】魔方工厂
- 【2016.5.21普及组模拟】博物馆
- Java千百问_08JDK详解(016)_AttachAPI是什么
- 小sugar呀——归并排序
- 1328. Party (Standard IO)
- 【编程马拉松】【024-放苹果】
- 企业信息安全之社工学审计
- Android平台上二维码的生成与扫描
- 拉力赛
- python socket和socketserver
- MSML 云计算深度学习平台
- (转)jQuery插件开发精品教程,让你的jQuery提升一个台阶
- 遥控车
- 6.3.1 自己动手写一个windows调试器