剑指offer:包含min函数的栈
来源:互联网 发布:手机淘宝2015旧版本5.5 编辑:程序博客网 时间:2024/06/12 06:25
题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
方法1:在top中写
这个题目挺无聊的,将查找最小值的实现放在top中写也可以通过测试用例。
【运行时间:16ms 占用内存:8272k】
import java.util.*;public class Solution { Stack<Integer> stack=new Stack<Integer>(); public void push(int node) { stack.push(node); } public void pop() { stack.pop(); } public int top() { int min=stack.peek(); int temp=0; for(Iterator<Integer> it=stack.iterator();it.hasNext();){ temp=it.next(); if(temp<min){ min=temp; } } return min; } public int min() { return top(); }}
方法2:正常
【运行时间:17ms 占用内存:8264k】
若果在top()中使用stack.pop()操作来提取元素会报错:java.util.EmptyStackException。因为主函数要执行peek()操作,所以不能随便出栈,不能让栈空。import java.util.*;public class Solution { Stack<Integer> stack=new Stack<Integer>(); public void push(int node) { stack.push(node); } public void pop() { stack.pop(); } public int top() { return stack.peek(); } public int min() { int min=stack.peek(); int temp=min; Iterator<Integer> it=stack.iterator(); while(it.hasNext()){ temp=it.next(); if(temp<min) min=temp; } return min; }}
阅读全文
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函数的栈
- Children of the Candy Corn
- Ubuntu下Python之dlib人脸检测
- Linux系统逻辑卷管理
- 17 多校 4
- <8/4>集训日记
- 剑指offer:包含min函数的栈
- hdu4548 美素数(C语言)
- 架构师入门笔记三 初识Queue队列
- 最短路径—Dijkstra算法和Floyd算法(理解)
- <a>标签的href和onclick属性
- libev源码解析——定时器原理
- 2017.08.04爱可生电话面试笔记
- tensorflow 实现wgan-gp mnist图片生成
- Windows下使用Redis(一)安装使用