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


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.

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

Credits:
Special thanks to @porker2008 for adding this problem and creating all test cases.

给了一个迭代器Iterator类接口有next(),hasNext()方法,让在此基础上设计实现一个PeekingIterator,有如下函数:

peek():返回下一个元素,但指针不移动到下一个
next(): 移动到下一个元素x并返回x
hasNext() :返回有下一个元素

解法:为了能peek()后下次next()还得到同样的数字,要用一个缓存保存下一个数字。当peek()时,返回缓存里的数就行,迭代器位置不会变。当next()的时候除了要返回数字和指针移动一位,还要将缓存更新为下一个数字,如果没有下一个就将缓存更新为null。

Java:

class PeekingIterator implements Iterator<Integer> {
private Iterator<Integer> iter;
private Integer nextElement;
private boolean peekUsed; public PeekingIterator(Iterator<Integer> iterator) {
// initialize any member here.
iter = iterator;
} // Returns the next element in the iteration without advancing the iterator.
public Integer peek() {
if(!peekUsed) {
nextElement = iter.next();
peekUsed = true;
}
return nextElement;
} // hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
@Override
public Integer next() {
if(peekUsed) {
peekUsed = false;
return nextElement;
}
return iter.next();
} @Override
public boolean hasNext() {
if(peekUsed) {
return true;
}
return iter.hasNext();
}
}

Java:  用Integer来做global variable, 不用使用boolean

// Java Iterator interface reference:
// https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
class PeekingIterator implements Iterator<Integer> {
private Iterator<Integer> iter;
private Integer next; public PeekingIterator(Iterator<Integer> iterator) {
// initialize any member here.
iter = iterator;
if (iter.hasNext()) {
next = iter.next();
}
} // Returns the next element in the iteration without advancing the iterator.
public Integer peek() {
return next;
} // hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
@Override
public Integer next() {
Integer res = next;
next = iter.hasNext() ? iter.next() : null;
return res;
} @Override
public boolean hasNext() {
return next != null;
}
}

Python:

class PeekingIterator(object):
def __init__(self, iterator):
"""
Initialize your data structure here.
:type iterator: Iterator
"""
self.iterator = iterator
self.val_ = None
self.has_next_ = iterator.hasNext()
self.has_peeked_ = False def peek(self):
"""
Returns the next element in the iteration without advancing the iterator.
:rtype: int
"""
if not self.has_peeked_:
self.has_peeked_ = True
self.val_ = self.iterator.next()
return self.val_; def next(self):
"""
:rtype: int
"""
self.val_ = self.peek()
self.has_peeked_ = False
self.has_next_ = self.iterator.hasNext()
return self.val_; def hasNext(self):
"""
:rtype: bool
"""
return self.has_next_   

C++:

// Below is the interface for Iterator, which is already defined for you.
// **DO NOT** modify the interface for Iterator.
class Iterator {
struct Data;
Data* data;
public:
Iterator(const vector<int>& nums);
Iterator(const Iterator& iter);
virtual ~Iterator();
// Returns the next element in the iteration.
int next();
// Returns true if the iteration has more elements.
bool hasNext() const;
}; class PeekingIterator : public Iterator {
public:
PeekingIterator(const vector<int>& nums) : Iterator(nums) {
// Initialize any member here.
// **DO NOT** save a copy of nums and manipulate it directly.
// You should only use the Iterator interface methods.
_flag = false;
} // Returns the next element in the iteration without advancing the iterator.
int peek() {
if (!_flag) {
_value = Iterator::next();
_flag = true;
}
return _value;
} // hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
int next() {
if (!_flag) return Iterator::next();
_flag = false;
return _value;
} bool hasNext() const {
if (_flag) return true;
if (Iterator::hasNext()) return true;
return false;
}
private:
int _value;
bool _flag;
};

  

All LeetCode Questions List 题目汇总

[LeetCode] 284. Peeking Iterator 瞥一眼迭代器的更多相关文章

  1. 【LeetCode】284. Peeking Iterator 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/peeking-i ...

  2. 【LeetCode】284. Peeking Iterator

    题目: Given an Iterator class interface with methods: next() and hasNext(), design and implement a Pee ...

  3. [LeetCode] 281. Zigzag Iterator 之字形迭代器

    Given two 1d vectors, implement an iterator to return their elements alternately. Example: Input: v1 ...

  4. 284. Peeking Iterator

    题目: Given an Iterator class interface with methods: next() and hasNext(), design and implement a Pee ...

  5. 设计模式 - 迭代模式(iterator pattern) Java 迭代器(Iterator) 详细解释

    迭代模式(iterator pattern) Java 迭代器(Iterator) 详细解释 本文地址: http://blog.csdn.net/caroline_wendy 參考迭代器模式(ite ...

  6. Java容器类源码分析之Iterator与ListIterator迭代器(基于JDK8)

    一.基本概念 迭代器是一个对象,也是一种设计模式,Java有两个用来实实现迭代器的接口,分别是Iterator接口和继承自Iterator的ListIterator接口.实现迭代器接口的类的对象有遍历 ...

  7. Collection接口都是通过Iterator()(即迭代器)来对Set和List遍历

    以下介绍接口: List接口:(介绍其下的两个实现类:ArrayList和LinkedList) ArrayList和数组非常类似,其底层①也用数组组织数据,ArrayList是动态可变数组. ① 底 ...

  8. [LeetCode] Peeking Iterator 顶端迭代器

    Given an Iterator class interface with methods: next() and hasNext(), design and implement a Peeking ...

  9. LeetCode OJ:Peeking Iterator(peeking 迭代器)

    Given an Iterator class interface with methods: next() and hasNext(), design and implement a Peeking ...

随机推荐

  1. clause

    clause 英 [klɔːz]  美 [klɔz]  口语练习 跟读 n. 条款:[计] 子句 specify 英 ['spesɪfaɪ]  美 ['spɛsɪfaɪ]  口语练习 跟读 vt. 指 ...

  2. IntToBinaryString

    void IntToBinaryString(int devisor,char* pBinStr) { int i; int remainder; ;i<;i++) { remainder=de ...

  3. oracle数据库(四)

    子查询与高级查询 我们在检索数据库的时候,需要将多个表关联起来进行查询,最常用的有子查询.连接查询和集合查询,子查询可以从另外一个表获取数据,连接查询可以指定多个表的连接方式,集合查询可以将两个或者多 ...

  4. Touch事件 移动端touch触摸事件

    <!-- HTML5 --> <!DOCTYPE html> <html> <head> <title>TouchEvent测试</t ...

  5. The Business Of Open Source

    http://oss-watch.ac.uk/resources/businessofopensource by Matthew Langham, Indiginox on 3 February 20 ...

  6. JavaScript基础03——函数的作用域及变量提升

    1.作用域 作用域,变量在函数内部作用的范围/区域.有函数的地方就有作用域.   2.局部作用域和全局作用域 function fn(){ var a = 1; } console.log(a); / ...

  7. virtualenvwrapper 方便的virtualenv 包装

      virtualenvwrapper 是一个方便的virtualenv 包装我们可以用来方便的管理python 的开发环境,同时 也支持对于项目的管理 安装 pip 安装 pip install v ...

  8. NetHack 备忘

    NetHack 备忘 常用操作 操作均区分大小写 上下左右移动 y k u h l b j n / 查看地图上的东西 < 上楼 > 下楼 c 关门 部分怪不会开门 a 使用(工具) d 丢 ...

  9. 金字塔原理(Pyramid Principle)

    什么是金字塔原理?简单来说,金字塔原理就是“中心论点---分论点---支撑论据”这样的一个结构. 图片摘自:http://www.woshipm.com/pmd/306704.html 人类通常习惯于 ...

  10. Android Studio一直显示Building“project name”Gradle project info问题详解

    关注我,每天都有优质技术文章推送,工作,学习累了的时候放松一下自己. 本篇文章同步微信公众号  欢迎大家关注我的微信公众号:「醉翁猫咪」 Android Studio一直显示 Building&quo ...