剑指Offer------包含min函数的栈
来源:互联网 发布:蓝月传奇龙魂数据 编辑:程序博客网 时间:2024/06/16 23:16
题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
<分析>
1.用一个栈data保存数据,另一个栈min保存依次出现的最小数
ex:data中依次入栈 5, 4 ,3,3,3,8,10,1
min中依次入栈5,4,3,3,3,no,no,1
no表示不入栈
每次入栈的时候,如果入栈的元素比min中的栈顶元素小或等于则入栈,否则不入栈。
import java.util.Stack;/** * * @author zy * @date 2017年10月4日 上午9:54:07 * @Decription 定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。 */public class Ex13 {//用来存储数据的栈Stack<Integer> data = new Stack<>();//用来存储最小数的栈Stack<Integer> min= new Stack<>();Integer tmp = null; public void push(int node) { if (tmp != null) {if (node <= tmp) {tmp = node;min.push(node);}data.push(node);}else {tmp = node;data.push(node);min.push(node);} } public void pop() { int num = data.pop(); int num2 = min.pop(); if (num != num2) {min.push(num2);}else {//当min栈顶pop时,应该更新tmp的值tmp = min.peek();} } public int top() { return data.peek(); } public int min() { return min.peek(); }}
阅读全文
0 0
- 【剑指offer】包含min函数的栈
- 剑指offer--包含min函数的栈
- 剑指Offer-->包含min函数的栈
- 《剑指offer》包含min函数的栈
- 剑指offer - 包含min函数的栈
- 剑指offer-包含min函数的栈
- 剑指offer:包含min函数的栈
- 包含min函数的栈|剑指offer
- 剑指offer-包含min函数的栈
- 剑指offer 包含min函数的栈
- 剑指offer:包含min函数的栈
- 剑指offer 包含min函数的栈
- [剑指offer]包含min函数的栈
- 《剑指offer》-包含min函数的栈
- 剑指offer----包含min函数的栈
- 【剑指offer】包含min函数的栈
- 剑指offer|包含min函数的栈
- 《剑指offer》包含min函数的栈
- 禁用IE设置代理检测不通过怎么办!
- STL_List
- C++初识之函数重载、缺省参数
- 单目相机姿态解算(OpenCV)
- C++ 常量
- 剑指Offer------包含min函数的栈
- leetcode: Minimum Window Substring
- AngularJS的自定义模板
- 常规的排序算法
- Linux线程的使用策略
- Elementary Math Gym
- Android 项目路径过长 引起error Error:too long on Windows, keep below 240 characters :
- Elasticsearch+python学习
- linux下的系统管理及系统安全命令