0%

leetCode-284:Peeking Iterator

问题描述

要求实现一个迭代器,其中有三个方法 :

  • peek:返回顶端元素,但是不移动指针(也就是说多次调用获取到的值是相同的)。

  • next:返回顶端元素,移动指针到下个位置(也就是说多次调用获取到的值是不同的)。

  • hasNext:判断是否存在下个元素。

样例输入输出

输入:
[“PeekingIterator”, “next”, “peek”, “next”, “next”, “hasNext”]
[[[1, 2, 3]], [], [], [], [], []]

输出:[null, 1, 2, 2, 3, false]

解释:
PeekingIterator peekingIterator = new PeekingIterator([1, 2, 3]); // [1,2,3]
peekingIterator.next(); // return 1, the pointer moves to the next element [1,2,3].
peekingIterator.peek(); // return 2, the pointer does not move [1,2,3].
peekingIterator.next(); // return 2, the pointer moves to the next element [1,2,3]
peekingIterator.next(); // return 3, the pointer moves to the next element [1,2,3]
peekingIterator.hasNext(); // return False

问题解法

此题的迭代器跟其他的迭代器差不多,只不过多了个 peek 函数要实现。针对这个函数,可以从 next 函数获取到值并缓存起来,后续调用时先判断是否存在该缓存,存在则返回缓存,否则直接调用 next 获取下个元素的值。代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// Java Iterator interface reference:
// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html

class PeekingIterator implements Iterator<Integer> {
private Iterator<Integer> it;

private Integer top;

public PeekingIterator(Iterator<Integer> iterator) {
// initialize any member here.
it = iterator;
top = null;
}

// Returns the next element in the iteration without advancing the iterator.
public Integer peek() {
if (top == null) {
top = it.next();
}

return top;
}

// hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
@Override
public Integer next() {
if (top != null) {
Integer temp = top;
top = null;
return temp;
}

return it.next();
}

@Override
public boolean hasNext() {
return top != null || it.hasNext();
}
}