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. python遇到动态函数---TypeError: unbound method a() must be called with A instance as first argument (got nothing instead)

    TypeError: unbound method a() must be called with A instance as first argument (got nothing instead) ...

  2. SUID提权

    查看tmp目录权限 ll -d /tmp 切换到tmp目录 cd /tmp 创建一个exploit目录 mkdir exploit 查看ping命令带suid权限 ll /bin/ping 创建tar ...

  3. 解决bash: less: command not found

    问题描述 使用less命令查找日志时,less命令未找到: 解决办法 安装less,执行如下命令: npm install -g less

  4. 持续集成学习8 jenkins权限控制

    一.总体配置 1.系统管理---> Configure Global Security 2.配置基于角色授权 创建角色 ----> 分配角色 代表着所有以dev-开头的 job全部都分配给 ...

  5. 【洛谷P5158】 【模板】多项式快速插值

    卡常严重,可有采用如下优化方案: 1.预处理单位根 2.少取几次模 3.复制数组时用 memcpy 4.进行多项式乘法项数少的时候直接暴力乘 5.进行多项式多点求值时如果项数小于500的话直接秦九昭展 ...

  6. 使用nodejs+ harbor rest api 进行容器镜像迁移

    最近因为基础设施调整,需要进行harbor 镜像仓库的迁移,主要是旧版本很老了,不想使用,直接 打算部署新的,原以为直接使用复制功能就可以,但是发现版本差异太大,直接失败,本打算使用中间 版本过度进行 ...

  7. python学习笔记二:(python3 logging函数中format说明)

    背景,在学习logging时总是遇到无法理解的问题,总结,尝试一下更清晰明了了,让我们开始吧! logging模块常用format格式说明 %(levelno)s: 打印日志级别的数值 %(level ...

  8. hadoop jps 出现空指针错误

    在hadoop中安装jdk软件以后出现如下问题: 错误描述 [xxx@localhost jdk1..0_181]$ ./bin/jps Exception in thread "main& ...

  9. vim配置无插件

    其实,vim插件会影响编辑器的启动速度,虽然有些插件影响不大,我依然觉得不够,其实通过简易的状态栏,可以显示必要的信息,能自定义颜色和背景甚至透明就足够了. 一.自定义状态栏其实以下内容可以写在一行上 ...

  10. 面试问我 Java 逃逸分析,瞬间被秒杀了。。

    记得几年前有一次栈长去面试,问到了这么一个问题: Java中的对象都是在堆中分配吗?说明为什么! 当时我被问得一脸蒙逼,瞬间被秒杀得体无完肤,当时我压根就不知道他在考什么知识点,难道对象不是在堆中分配 ...