[LeetCode] Peeking Iterator
2015-11-06 17:59
183 查看
Given an Iterator class interface with methods:
Here is an example. Assume that the iterator is initialized to the beginning of the list:
Call
Now you call
You call
Hint:
Think of “looking ahead”. You want to cache the next element.
Is one variable sufficient? Why or why not?
Test your design with call order of peek() before next() vs next() before peek().
For a clean implementation, check out Google’s guava library source code.
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.
Hint:
Think of “looking ahead”. You want to cache the next element.
Is one variable sufficient? Why or why not?
Test your design with call order of peek() before next() vs next() before peek().
For a clean implementation, check out Google’s guava library source code.
解题思路
用一个变量来保存peek元素值,每次调用next()和
peek()时更新其值。
实现代码
Java:// Runtime: 120 ms //Java Iterator interface reference: //https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html class PeekingIterator implements Iterator<Integer> { Integer peek = null; private Iterator<Integer> iterator; public PeekingIterator(Iterator<Integer> iterator) { this.iterator = iterator; } // Returns the next element in the iteration without advancing the iterator. public Integer peek() { if (peek == null) { peek = iterator.next(); } return peek; } // hasNext() and next() should behave the same as in the Iterator interface. // Override them if needed. @Override public Integer next() { if (peek == null) { return iterator.next(); } else { Integer temp = peek; peek = null; return temp; } } @Override public boolean hasNext() { if (peek != null) { return true; } else { return iterator.hasNext(); } } }
相关文章推荐
- Android Donut Makefile分析 (build/envsetup.sh)
- 百度作业帮一面总结
- call to a member function display() on a non-object
- android_01Activity_知识小结
- 利用GoAhead构建嵌入式web应用
- C++ operator关键字(重载操作符)
- HDU---2222-Keywords Search(AC自动机)
- Red Hat Enterprise Linux 6.4上编译proc
- js 事件冒泡和事件捕获
- CentOS5.4安装samba服务
- 判断当前android系统的尺寸。用来区分平板和手机,亲测。
- Leetcode142: Restore IP Addresses
- build/envsetup.sh 简介
- iOS学习之Table View的简单使用(前辈写的哦,仅是收藏一下,好仔细啊,赞!)
- curl
- LeetCode OJ:Group Anagrams(同字符字符群)
- Mac 键盘快捷键
- Android支付宝、微信支付阐述
- as3将sprite类型复制到另一个sprite
- Dispose接口规范