|
| 1 | +# 题目描述(中等难度) |
| 2 | + |
| 3 | + |
| 4 | + |
| 5 | +给迭代器增加一个 `peek` 功能,也就是查看下一个元素,但是不从迭代器中弹出。 |
| 6 | + |
| 7 | +# 解法一 |
| 8 | + |
| 9 | +我第一反应是直接把迭代器的元素放到 `list` 中不就实现了吗? |
| 10 | + |
| 11 | +```java |
| 12 | +class PeekingIterator implements Iterator<Integer> { |
| 13 | + List<Integer> list; |
| 14 | + int cur = 0; |
| 15 | + |
| 16 | + public PeekingIterator(Iterator<Integer> iterator) { |
| 17 | + // initialize any member here. |
| 18 | + list = new ArrayList<>(); |
| 19 | + while (iterator.hasNext()) |
| 20 | + list.add(iterator.next()); |
| 21 | + |
| 22 | + } |
| 23 | + |
| 24 | + // Returns the next element in the iteration without advancing the iterator. |
| 25 | + public Integer peek() { |
| 26 | + return list.get(cur); |
| 27 | + } |
| 28 | + |
| 29 | + // hasNext() and next() should behave the same as in the Iterator interface. |
| 30 | + // Override them if needed. |
| 31 | + @Override |
| 32 | + public Integer next() { |
| 33 | + return list.get(cur++); |
| 34 | + } |
| 35 | + |
| 36 | + @Override |
| 37 | + public boolean hasNext() { |
| 38 | + return cur < list.size(); |
| 39 | + } |
| 40 | +} |
| 41 | +``` |
| 42 | + |
| 43 | +# 解法二 |
| 44 | + |
| 45 | +解法一还真的通过了,觉得自己没有 get 题目的点,然后去逛 Discuss 了,原来题目想让我们这样做,分享 [这里](https://leetcode.com/problems/peeking-iterator/discuss/72558/Concise-Java-Solution) 的代码。 |
| 46 | + |
| 47 | +我们知道构造函数传进来的迭代器已经有了 `next` 和 `haseNext` 函数,我们需要增加 `peek` 函数。我们可以加一个缓冲变量,记录当前要返回的值。 |
| 48 | + |
| 49 | +`peek` 的话只需要将缓冲变量直接返回。 |
| 50 | + |
| 51 | +`next` 的话我们需要更新缓冲变量,然后将之前的缓冲变量返回即可。 |
| 52 | + |
| 53 | +```java |
| 54 | +class PeekingIterator implements Iterator<Integer> { |
| 55 | + private Integer next = null;//缓冲变量 |
| 56 | + private Iterator<Integer> iter; |
| 57 | + |
| 58 | + public PeekingIterator(Iterator<Integer> iterator) { |
| 59 | + // initialize any member here. |
| 60 | + iter = iterator; |
| 61 | + if (iter.hasNext()){ |
| 62 | + next = iter.next(); |
| 63 | + } |
| 64 | + |
| 65 | + } |
| 66 | + |
| 67 | + // Returns the next element in the iteration without advancing the iterator. |
| 68 | + public Integer peek() { |
| 69 | + return next; |
| 70 | + } |
| 71 | + |
| 72 | + // hasNext() and next() should behave the same as in the Iterator interface. |
| 73 | + // Override them if needed. |
| 74 | + @Override |
| 75 | + public Integer next() { |
| 76 | + Integer res = next; |
| 77 | + next = iter.hasNext() ? iter.next() : null; |
| 78 | + return res; |
| 79 | + } |
| 80 | + |
| 81 | + @Override |
| 82 | + public boolean hasNext() { |
| 83 | + return next != null; |
| 84 | + } |
| 85 | +} |
| 86 | +``` |
| 87 | + |
| 88 | +# 总 |
| 89 | + |
| 90 | +其实是比较简单的一道题,用到的思想也比较简单,增加了一个缓冲变量来实现 `peek` 的功能。 |
0 commit comments