LeetCode Peeking Iterator
2016-01-11 12:16
351 查看
Description:
Given an Iterator class interface with methods:
design and implement a PeekingIterator that support the
element that will be returned by the next call to next().
Here is an example. Assume that the iterator is initialized to the beginning of the list:
Call
Now you call
that still return 2.
You call
that should return false.
Solution:
开始没反应过来,后来发现只要建立一个类似于缓存机制的东西即可。
在这里,就用peekFlag和peekNum来代表是否已经peek过,已经peek的数值。
Given an Iterator class interface with methods:
next()and
hasNext(),
design and implement a PeekingIterator that support the
peek()operation -- it essentially peek() at the
element that will be returned by the next call to next().
Here is an example. Assume that the iterator is initialized to the beginning of the list:
[1, 2, 3].
Call
next()gets you 1, the first element in the list.
Now you call
peek()and it returns 2, the next element. Calling
next()after
that still return 2.
You call
next()the final time and it returns 3, the last element. Calling
hasNext()after
that should return false.
Solution:
开始没反应过来,后来发现只要建立一个类似于缓存机制的东西即可。
在这里,就用peekFlag和peekNum来代表是否已经peek过,已经peek的数值。
<span style="font-size:18px;">import java.util.*; // Java Iterator interface reference: // https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html class PeekingIterator implements Iterator<Integer> { Iterator<Integer> ite; boolean peekFlag = false; Integer peekNum; public PeekingIterator(Iterator<Integer> iterator) { // initialize any member here. ite = iterator; peekFlag = false; } // Returns the next element in the iteration without advancing the iterator. public Integer peek() { if (!peekFlag) { peekFlag = true; peekNum = ite.next(); } return peekNum; } // hasNext() and next() should behave the same as in the Iterator interface. // Override them if needed. @Override public Integer next() { if (peekFlag) { peekFlag = false; return peekNum; } return ite.next(); } @Override public boolean hasNext() { return peekFlag || ite.hasNext(); } }</span>
相关文章推荐
- startActivityForResult()方法具体解释
- JS 判断上传 文件 大小
- IOS-底层数据结构
- 如何确保项目开发敏捷和安全两者兼得呢?
- 关于CentOS/RHEL中GlusterFS版本说明
- JDBC对象
- 先贴上代码:Random快排,快排的非递归实现
- java 检查a字符串是否包含b字符串
- 机器学习xgboost实战—手写数字识别
- 字符串数组转化成十六进制字符串
- JS 判断上传 文件 大小
- swift 之SnapKit 动画
- poj 3295
- In C++, what’s the difference between an inline function and a macro?
- eclipse 使用Maven deploy命令打包源码到私服nexus
- nsset
- 【蓝桥杯】【锦标赛】
- Cocos2dx 3.0 过渡篇(三十)灰机还是3D好(Sprite3D)
- Sublime Text 2/3安装CTags实现函数跳转
- 模糊查询