剑指offer21:包含min函数的栈
来源:互联网 发布:linux常用命令手册 编辑:程序博客网 时间:2024/06/03 16:42
Java实现
题目:
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的min函数。在该栈中,调用min、push及pop的时间复杂度都是O(1)
import java.util.Stack;public class Main{ //数据站 public static Stack<Integer> dataStack = new Stack<>(); //最小值栈 public static Stack<Integer> minStack = new Stack<>(); public static void main(String[] args) { Main.push(3); Main.push(4); Main.push(2); Main.push(1); Integer popNum = Main.pop();//弹出1 System.out.println("弹出栈: " + popNum); Main.push(0); System.out.printf("最小值: %d \n", Main.min()); } public static void push(Integer value){ dataStack.push(value); if(minStack.isEmpty() || value < minStack.peek()){ minStack.push(value); }else { minStack.push(minStack.peek()); //将最小栈 栈顶元素 再次压入最小栈 } } public static Integer pop(){ if(dataStack.size() ==0 || minStack.size()==0){ return null; } return dataStack.pop(); } public static Integer min(){ if(dataStack.size() > 0 && minStack.size()>0){ return dataStack.peek(); } return null; }}
0 0
- 剑指offer21-包含min函数的栈
- 剑指Offer21包含min函数的栈
- 剑指offer21:包含min函数的栈
- 剑指offer21包含min函数的栈
- offer21:包含min函数的栈
- 包含min的栈~~剑指offer21题
- 【剑指offer】包含min函数的栈
- 剑指offer--包含min函数的栈
- 剑指Offer-->包含min函数的栈
- 《剑指offer》包含min函数的栈
- 剑指offer - 包含min函数的栈
- 剑指offer-包含min函数的栈
- 剑指offer:包含min函数的栈
- 包含min函数的栈|剑指offer
- 剑指offer-包含min函数的栈
- 剑指offer 包含min函数的栈
- 剑指offer:包含min函数的栈
- 剑指offer 包含min函数的栈
- Git学习笔记
- java面试集合(上)
- Delphi常用关键字用法详解
- Eclipse 一些个人的偏好设置
- 最简单的ivy在ecipse中使用,没有涉及到ivySettings的使用
- 剑指offer21:包含min函数的栈
- ssh登录docker容器
- [深入理解Android卷一全文-第四章]深入理解zygote
- java继承中父类和子类静态、非静态代码块,构造函数,静态方法的执行顺序
- Galactic History(方法巧妙,思维灵活)
- spark从kafka中获取数据
- Android实战之app版本更新升级全文章(一)
- IOS[Swift版]常用操作代码片段
- 07.JPA持久化