题目本身很简单,就是实现一个支持 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().
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.
我的实现:
class PeekingIterator implements Iterator<Integer> {
private final Iterator<Integer> iterator;
private Integer value;
public PeekingIterator(Iterator<Integer> iterator) {
this.iterator = iterator;
this.value = null;
}
public Integer peek() {
if (value != null) return value;
value = iterator.next();
return value;
}
@Override
public boolean hasNext() {
return value != null || iterator.hasNext();
}
@Override
public Integer next() {
Integer temp;
if (value != null) {
temp = value;
value = null;
} else {
temp = iterator.next();
}
return temp;
}
}
Runtime 是 93.72%
iterator 去掉 final 修饰,value 不在 Constructor 中赋值 null,Runtime 就变为 100.00% 了。
public class PeekingIterator implements Iterator<Integer> {
private Iterator<Integer> iterator;
private Integer value = null;
public PeekingIterator(Iterator<Integer> iterator) {
this.iterator = iterator;
}
......
}
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.