码农小汪-剑指Offer之18-包含min函数的栈
来源:互联网 发布:java读取csv文件内容 编辑:程序博客网 时间:2024/06/12 01:25
题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
如下我们可以看出来,我们必须的还有原来的行为。
public void push(int node) { } public void pop() { } public int top() { } public int min() { }
题解
我们的保持原来的行为,栈以前能做的事情,我们都得做好,这个首要完成的事情,其次,我们还的研究,怎么把最新的东西保存下来下次利用,一下子就返回回来了。
- 我们保存原来的内容,就是用栈就行了,以前怎么玩得就怎么玩
我们增加额外的空间去做这件事,就可以了,比如在来一个栈,我们每次插入的时候比较一下就要了,比栈顶的小,就插入,否则放弃插入到minStack。每次删除元素的时候如果normalStack的值和我现在的值相等,我们就删除minStack就可以啦
下面的代码:
package JianzhiOffer;import java.util.Stack;/** * * @author JetWang * */public class Slution18 { Stack<Integer> normalStack = new Stack<Integer>(); Stack<Integer> minStack = new Stack<Integer>(); public void push(int node) { normalStack.push(node); if (minStack.isEmpty()) { minStack.push(node); } else { int old = minStack.peek(); if (node < old) { minStack.push(node); } } } public void pop() { if (!normalStack.isEmpty()) { int value = normalStack.pop(); int min = minStack.peek(); if (min == value) { minStack.pop(); } } } public int top() { return normalStack.peek(); } public int min() { return minStack.peek(); }}
0 0
- 码农小汪-剑指Offer之18-包含min函数的栈
- 剑指Offer之包含min函数的栈
- 剑指Offer之 - 包含min函数的栈
- 剑指offer系列之十九:包含min函数的栈
- 【剑指offer】之包含min函数的栈
- 剑指offer系列之19:包含min函数的栈
- 剑指offer(十七)之包含min函数的栈
- 剑指offer 之 包含min函数的栈
- 剑指offer之十七---包含min函数的栈
- 【剑指offer】包含min函数的栈
- 剑指offer--包含min函数的栈
- 剑指Offer-->包含min函数的栈
- 《剑指offer》包含min函数的栈
- 剑指offer - 包含min函数的栈
- 剑指offer-包含min函数的栈
- 剑指offer:包含min函数的栈
- 包含min函数的栈|剑指offer
- 剑指offer-包含min函数的栈
- android用okhttp和retrofit访问网络的时候有时候出现EOFException异常
- poj 2891 一般模线性方程
- poj 1149 PIGS 网络流建图
- IOS 发布应用程序到App Store
- dom4j-Quick Start Guide
- 码农小汪-剑指Offer之18-包含min函数的栈
- 第4周项目5-用递归方法求解4
- CF_5A_ChatServer'sOutgoingTraffic
- HDOJ 2049 不容易系列之(4)——考新郎
- 开发者需要知道的iOS 8 SDK新特性
- 关于String,StringBuffer与StringBuilder
- Java学习_多线程
- IOS学习之——面试问题集锦
- 三角形三边