Solution 2: Min Stack
2015-06-28 18:57
190 查看
问题描述
定义栈的数据结构,要求添加一个min函数,能够得到栈的最小元素。
实现栈的push(), pop()及getMin()函数,要求函数的时间复杂度为O(1).
解决思路
使用两个栈,一个为普通栈,实现push和pop函数;另一个记录所有入栈元素的非递增序列;
如下图所示:
程序
定义栈的数据结构,要求添加一个min函数,能够得到栈的最小元素。
实现栈的push(), pop()及getMin()函数,要求函数的时间复杂度为O(1).
解决思路
使用两个栈,一个为普通栈,实现push和pop函数;另一个记录所有入栈元素的非递增序列;
如下图所示:
程序
public class MinStack { private Stack<Integer> normal; private Stack<Integer> min; public MinStack() { normal = new Stack<Integer>(); min = new Stack<Integer>(); } public void push(int elem) { normal.push(elem); if (min.isEmpty() || min.peek() >= elem) { min.push(elem); } } public int pop() throws Exception { if (normal.isEmpty()) { throw new Exception("Error: The Stack is Empty!"); } int res = normal.pop(); if (min.peek() == res) { min.pop(); } return res; } public int getMin() throws Exception { if (min.isEmpty()) { throw new Exception("Error: The Stack is Empty!"); } return min.peek(); } }
相关文章推荐
- Java判断文件、文件夹是否存在
- SPORTSTORE OPENCART 商城自适应主题模板 ABC-0003-01
- [学习笔记—Objective-C]《Objective-C 程序设计 第6版》第六章 选择结构 课后题6-4&6-6&6-7
- 欢迎使用CSDN-markdown编辑器
- [Rails] 从 Request 到 Response(2)
- 串口通讯—同步通信方式
- UML期末复习题——2.3:UML State Diagram
- matlab读入三维点云数据斯坦福兔子
- 单片机的定时器与计数器
- jsp和Servlet的比较
- Unity炸弹爆炸伤害(群攻伤害)
- 提取课表功能
- Growing Pains for Deep Learning
- php页面静态化—实现页面纯静态化的原理
- maven如何设置本地仓库
- Linux(Ubuntu)下如何解压 .zip 文件
- Using the ? wildcard : Generic Parameters
- OCP-1Z0-051-2015-26题
- java像素级碰撞检测代码
- Using Bounded Wildcards in Methods : Generic Parameters