【算法】查找栈内最小值的O(1)算法————用辅助栈实现
来源:互联网 发布:食品代加工 知乎 编辑:程序博客网 时间:2024/06/08 20:00
查找栈内最小值的O(1)算法————用辅助栈实现
具体实现方式有二,但两者区别仅在于入栈出栈的方式,思路均为通过一个辅助栈来实现存储原栈的最小值,辅助栈的栈顶永远为当前栈的最小值。
(设辅助栈为stackMin
,原栈为stackData
)
方式一:stackData
每压入一个数,就比较该数与stackMin
栈顶的大小(如果stackMin
为空,就直接压入),如果小就压入stackPop
中,否则略过;每弹出一个数,就比较该数与stackMin
栈顶的大小是否相等,如果相等就同时弹出stackMin
的栈顶,否则略过
代码实现如下:
package com.lilydedbb;import java.util.Stack;/** * Created by dbb on 2016/12/23. */public class GetMinStack { private Stack<Integer> stackData; private Stack<Integer> stackMin; public GetMinStack(){ this.stackData = new Stack<Integer>(); this.stackMin = new Stack<Integer>(); } public void push(int newNumber){ this.stackData.push(newNumber); if(this.stackMin.isEmpty() || newNumber <= this.getMin()) this.stackMin.push(newNumber); } public int pop(){ if(this.stackData.isEmpty()) throw new RuntimeException("The stack is empty"); int number = this.stackData.pop(); if (number == this.getMin()) this.stackMin.pop(); return number; } public int getMin(){ if(this.stackMin.isEmpty()) throw new RuntimeException("The stack is empty"); return this.stackMin.peek(); }}
方式二:stackData
每压入一个数,就比较该数与stackMin
栈顶的大小(如果stackMin
为空,就直接压入),如果小就压入stackPop
中,否则继续压入上一次压入的最小值;每弹出一个数,就同时弹出stackMin
的栈顶
代码实现如下:
package com.lilydedbb;import java.util.Stack;/** * Created by dbb on 2016/12/23. */public class GetMinStack2 { private Stack<Integer> stackData; private Stack<Integer> stackMin; public GetMinStack2(){ this.stackData = new Stack<Integer>(); this.stackMin = new Stack<Integer>(); } public void push(int newNumber){ this.stackData.push(newNumber); if(this.stackMin.isEmpty() || newNumber <= this.getMin()){ this.stackMin.push(newNumber); }else{ this.stackMin.push(this.getMin()); } } public int pop(){ if(this.stackData.isEmpty()) throw new RuntimeException("The stack is empty"); this.stackMin.pop(); return this.stackData.pop(); } public int getMin(){ if(this.stackMin.isEmpty()) throw new RuntimeException("The stack is empty"); return this.stackMin.peek(); }}
方式一与方式二都在保证辅助栈的栈顶均为最小值,区别仅在于push
和pop
时的策略不同。
0 0
- 【算法】查找栈内最小值的O(1)算法————用辅助栈实现
- 常用数据结构2——栈,实现PUSH、POP和取最小值操作算法时间复杂度为o(1)
- 查找算法——javascript算法实现
- 查找算法的实现——二分查找
- Java对查找算法的实现—顺序查找(一)
- Java对查找算法的实现—二分查找(二)
- 查找算法—折半查找算法分析与实现(Python)
- 最大值最小值查找算法(C++实现)
- Java算法——一维数组的常见操作(遍历,求最大值,最小值,逆序,查找)
- 字符串算法——查找有序数组旋转后的最小值(无重复元素)(Find Minimum in Rotated Sorted Array)
- 分而治之算法——找最大值最小值
- 实现O(1)获取最大最小值的栈----java
- O(1)时间求出栈内元素最小值
- O(1)时间求出栈内元素最小值
- O(1)时间求出栈内元素最小值
- 数据结构——排序查找算法实现
- 算法学习-查找旋转数组的最小值
- 数据结构和算法——算法 查找算法(二分查找法)实现
- 全球DEM现状
- 实验 利用百度地图对自己定位
- JSP 防止网页刷新重复提交数据
- javaweb srpingmvc mybatis 分页查询 增加示例 参数类型map 和实体对象
- ArrayList、LinkedList、 Vector、Map 用法比较
- 【算法】查找栈内最小值的O(1)算法————用辅助栈实现
- SpringMVC框架配置
- JVM 优点与缺点的深入分析
- Spring事务配置的五种方式
- Java servlet
- s3c2440时钟分频
- Power
- 【算法】通过辅助栈实现排序已知栈
- Linux初识软连接和硬链接