剑指offer:包含min函数的栈
2017-08-04 22:37
211 查看
题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
【运行时间:16ms 占用内存:8272k】
若果在top()中使用stack.pop()操作来提取元素会报错:java.util.EmptyStackException。因为主函数要执行peek()操作,所以不能随便出栈,不能让栈空。
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的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; } }
相关文章推荐
- 剑指offer 包含min函数的栈
- 剑指Offer 21 包含min函数的栈
- 【剑指offer】4.3举例让抽象问题具体化——面试题21:包含min函数的栈
- 【剑指Offer面试编程题】题目1522:包含min函数的栈--九度OJ
- 剑指offer面试题21 包含min函数的栈
- 【剑指offer】数据结构 ——包含min函数的栈(C++)
- 剑指offer第20题(包含min函数的栈)
- 剑指Offer——包含min函数的栈
- 剑指offer——包含min函数的栈
- 【剑指offer 面试题21】包含min函数的栈
- 剑指Offer - 九度1522 - 包含min函数的栈
- 牛客网剑指offer-包含min函数的栈
- 剑指offer:包含min函数的栈
- 剑指Offer 21:包含min函数的栈
- 剑指offer题21 包含min函数的栈
- 剑指offer——包含min函数的栈
- 剑指offer--包含min函数的栈
- 剑指offer--面试题21:包含min函数的栈
- 剑指offer面试题[21]包含min函数的栈
- 剑指offer——面试题21:包含min函数的栈(泛型编程,一个巧妙的思维)