[LeetCode] 284. Peeking Iterator

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().

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.

Follow up: How would you extend your design to be generic and work with all types, not just integer?

顶端迭代器。

给定一个迭代器类的接口,接口包含两个方法: next() 和 hasNext()。设计并实现一个支持 peek() 操作的顶端迭代器 -- 其本质就是把原本应由 next() 方法返回的元素 peek() 出来。

示例:

假设迭代器被初始化为列表 [1,2,3]。

调用 next() 返回 1,得到列表中的第一个元素。
现在调用 peek() 返回 2,下一个元素。在此之后调用 next() 仍然返回 2。
最后一次调用 next() 返回 3,末尾元素。在此之后调用 hasNext() 应该返回 false。
进阶:你将如何拓展你的设计?使之变得通用化,从而适应所有的类型,而不只是整数型?

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/peeking-iterator
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

next()hasNext()函数不必多说了,感觉这道题的重点在于考察如何实现这个peek()函数。首先还是创建一个迭代器开始迭代list,同时需要创建一个变量next来记录下一个会被迭代到的数字。

初始化的时候,如果迭代器有下一个元素hasNext(),那么就直接把这个元素拿到,放入next变量中暂时记录下来。这样peek()的时候,直接return这个next就行了。

hasNext()函数则是通过判断这个next变量是否为空,来判断是否整个list已经被遍历完了。

最后重点在于如何处理next()函数。因为next已经记录了下一个应该会被返回的值,所以返回这个数字不难,但是此时的next()函数,应该做如下这两步

  • res = next - 把这个next数字拿过来,然后返回res,这样next()就跟peek()返回的是一样的数字了
  • 如果迭代器还有下一个元素,则把这个元素拿出来,用next变量记住,否则就返回NULL

在迭代器不为空的情况下,peek()和next()需要返回的是相同的东西,所以这里重写的next()函数实际上是在看再下一个元素

时间O(n)

空间O(1)

Java实现

 1 // Java Iterator interface reference:
 2 // https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
 3 class PeekingIterator implements Iterator<Integer> {
 4     private Iterator<Integer> iter;
 5     private Integer next = null;
 6 
 7     public PeekingIterator(Iterator<Integer> iterator) {
 8         // initialize any member here.
 9         iter = iterator;
10         if (iter.hasNext()) {
11             next = iter.next();
12         }
13     }
14 
15     // Returns the next element in the iteration without advancing the iterator.
16     public Integer peek() {
17         return next;
18     }
19 
20     // hasNext() and next() should behave the same as in the Iterator interface.
21     // Override them if needed.
22     @Override
23     public Integer next() {
24         Integer res = next;
25         next = iter.hasNext() ? iter.next() : null;
26         return res;
27     }
28 
29     @Override
30     public boolean hasNext() {
31         return next != null;
32     }
33 }

 

LeetCode 题目总结

posted @ 2020-08-26 15:26  CNoodle  阅读(189)  评论(0编辑  收藏  举报