在O(1)时间内返回栈的最小值
来源:互联网 发布:帝国时代 知乎 编辑:程序博客网 时间:2024/06/07 13:22
implement a stack which not only has push, pop, but also is able to return the minimum value within O(1) time.
public class NewStack extends Stack<Node> {public void push(Node node) {if (node.getValue() < this.min()) {node.setMin(node.getValue());}super.push(node);}public Node pop() {return super.pop();}public int min() {if (peek() == null) {return MAX_INT;} else {peek().getMin();}}}class Node {int value;int min;public int getValue() {return value;}public int getMin() {return min;}public void setMin(int min) {this.min = min;}}
in the previous approach, the main drawback is that in each node, they have to store the min value, it costs too many spaces. As the minimum value may stay the same if no larger element appears, so we can improve the algorithm above by removing duplicated min values.
public class StackWithMin {Stack<Integer> stack1 = new Stack<Integer>();Stack<Integer> stack2 = new Stack<Integer>();public void push(int value) {if (value <= min()) {stack2.push(value);}stack1.push(value);}public int pop() {if (stack1.peek() == stack2.peek() ) {stack2.pop();}return stack1.pop();}public int min() {if (stack2.peek() == null) {return MAX_INT;} else {return stack2.peek();}}}
- 在O(1)时间内返回栈的最小值
- 如何在O(1)的时间内获得栈的最大值、最小值
- 编程之美系列之栈和队列1—在O(1)的时间内得到栈的最大或者最小值
- 编程之美系列之栈和队列2—在O(1)的时间内得到队列的最大或者最小值
- 模拟O(1)能返回最小值的栈
- 在 O(1) 的时间内删除单链表的结点
- 栈在O(1)时间内求min值
- Stack(篇3)设计一个栈能够在O(1)的时间内getMin
- 带有O(1)时间返回最小值的stack
- 在O(1)时间内删除单链表结点
- 在O(1)时间内删除单链表结点
- 在o(1)时间内删除链表中结点
- 在O(1)时间内删除单链表结点
- 实现一个栈,要求Push/Pop/Min(返回最小值)的时间复杂度为O(1)
- 实现一个栈(元素遵守先入后出顺序),能够通过 min 方法在 O(1)时间内获取栈中的最小元素。同时,栈的基本操作:入栈(Push)、出栈(Pop),也是在O(1)时间内完成的
- 实现一个出栈,入栈,返回最小值的操作的时间复杂度为O(1)的栈
- 设计一个带MIN的栈,要求出栈,入栈,返回最小值的时间复杂度为O(1)
- 实现一个栈Stack,Push、Pop、Min(返回最小值的操作)的时间复杂度为O(1)
- Eclipse MyEclipse Code Template 设置
- SQL导出到MYSQL
- 精妙SQL语句介绍
- 创新工场O2O项目布丁六款生活类应用简评
- SQL Server 6.5 配置使用要点
- 在O(1)时间内返回栈的最小值
- 解决MSSQL占用过多内存的简单方法
- VC使用MSXML解析XML文档
- 将作为字符串保存的IP地址变为二进制数值
- SQL Server数据库崩溃时恢复方式
- gcc中的-finput-charset和-fexec-charset开关
- SQL Server提升权限相关命令及防范
- POJ 3842 An Industrial Spy
- linux + eclipse调试ffmpeg