[LeetCode] 284. Peeking Iterator 瞥一眼迭代器
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 瞥一眼迭代器的更多相关文章
- 【LeetCode】284. Peeking Iterator 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/peeking-i ...
- 【LeetCode】284. Peeking Iterator
题目: Given an Iterator class interface with methods: next() and hasNext(), design and implement a Pee ...
- [LeetCode] 281. Zigzag Iterator 之字形迭代器
Given two 1d vectors, implement an iterator to return their elements alternately. Example: Input: v1 ...
- 284. Peeking Iterator
题目: Given an Iterator class interface with methods: next() and hasNext(), design and implement a Pee ...
- 设计模式 - 迭代模式(iterator pattern) Java 迭代器(Iterator) 详细解释
迭代模式(iterator pattern) Java 迭代器(Iterator) 详细解释 本文地址: http://blog.csdn.net/caroline_wendy 參考迭代器模式(ite ...
- Java容器类源码分析之Iterator与ListIterator迭代器(基于JDK8)
一.基本概念 迭代器是一个对象,也是一种设计模式,Java有两个用来实实现迭代器的接口,分别是Iterator接口和继承自Iterator的ListIterator接口.实现迭代器接口的类的对象有遍历 ...
- Collection接口都是通过Iterator()(即迭代器)来对Set和List遍历
以下介绍接口: List接口:(介绍其下的两个实现类:ArrayList和LinkedList) ArrayList和数组非常类似,其底层①也用数组组织数据,ArrayList是动态可变数组. ① 底 ...
- [LeetCode] Peeking Iterator 顶端迭代器
Given an Iterator class interface with methods: next() and hasNext(), design and implement a Peeking ...
- LeetCode OJ:Peeking Iterator(peeking 迭代器)
Given an Iterator class interface with methods: next() and hasNext(), design and implement a Peeking ...
随机推荐
- CentOS7安装Pycharm
1. 进入官网:https://www.jetbrains.com/pycharm/2. 点击下载3. 直接安装:tar zxvf ***.tar.gz4. 建立软连接:sudo ln -s /you ...
- 路由器安全——破解wifi密码,同时中间人攻击
聊聊安全那些事儿 篇一:Wi-Fi安全浅析 2016-04-25 13:18:16 141点赞 712收藏 63评论 前言 近期,Wi-Fi相关的安全话题充斥着电视新闻的大屏幕,先是曝出了路由器劫持的 ...
- Kotlin函数使用综述与显式返回类型分析
位置参数与具名参数: 继续接着上一次https://www.cnblogs.com/webor2006/p/11498842.html的方法参数学习,再定义一个函数来说明具名参数的问题: 调用一下,先 ...
- Python +urllib+urllib2 带数据的post请求实例
#coding:utf-8 ''' Created on 2017年11月2日 @author: li.liu ''' import urllib import urllib2 import re f ...
- Echo团队Alpha冲刺随笔 - 第九天
项目冲刺情况 进展 已经进入测试阶段,正在消除系统的bug 问题 通过测试,找出了系统中存在的较多bug...... 体会 测试太重要了,很多原本以为没什么bug,一测就能找到好几个,而且改个bug真 ...
- 我理解的Linux内存管理
众所周知,内存管理是Linux内核中最基础,也是相当重要的部分.理解相关原理,不管是对内存的理解,还是对大家写用户态代码都很有帮助.很多书上.很多文章都写了相关内容,但个人总觉得内容太复杂,不是太容易 ...
- python SQLAlchemy的简单配置和查询
背景: 今天小鱼从0开始配置了下 SQLAlchemy 的连接方式,并查询到了结果,记录下来 需要操作四个地方 1. config ------数据库地址 2.init ----- 数据库初始化 3 ...
- 字节序 —— Big Endian 和 Little Endian
一.字节序 字节序指的是多字节的数据在内存中的存放顺序 内存有高地址端与低地址端.其中,低地址端既可以存放高位字节,也可以存放低位字节. Big Endian 是指低地址端 存放 高位字节. Litt ...
- OLED液晶屏幕(0)自动获取12ic地址液晶屏幕
. 烧录 串口可以看到输出的地址 #include <Wire.h> void setup(){ Wire.begin(); Serial.begin(9600); Serial.prin ...
- Cocos CreatorUI系统上
若本号内容有做得不到位的地方(比如:涉及版权或其他问题),请及时联系我们进行整改即可,会在第一时间进行处理. 请点赞!因为你们的赞同/鼓励是我写作的最大动力! 欢迎关注达叔小生的简书! 这是一个有质量 ...