[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 ...
随机推荐
- Pure C static coding analysis tools
Cppcheck - A tool for static C/C++ code analysiscppcheck.sourceforge.netCppcheck is a static analysi ...
- 微信程序开发之-WeixinJSBridge调用
微信的WeixinJSBridge还是很厉害的,虽然官方文档只公布了3个功能,但是还内置的很多功能没公布,但是存在.今天就好好和大家聊聊 功能1------发送给好友 代码如下: functi ...
- TensorFlow的GPU设置
在使用GPU版的TensorFlow跑程序的时候,如果不特殊写代码注明,程序默认是占用所有主机上的GPU,但计算过程中只会用其中一块.也就是你看着所有GPU都被占用了,以为是在GPU并行计算,但实际上 ...
- Problem I. Wiki with Special Poker Cards
Problem I. Wiki with Special Poker CardsInput file: standard input Time limit: 1 secondOutput file: ...
- HTML事件(onclick、onmouseover、onmouseout、this)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- Web 项目的文件/文件夹上传下载
我们平时经常做的是上传文件,上传文件夹与上传文件类似,但也有一些不同之处,这次做了上传文件夹就记录下以备后用. 这次项目的需求: 支持大文件的上传和续传,要求续传支持所有浏览器,包括ie6,ie7,i ...
- BZOJ 1034: [ZJOI2008]泡泡堂BNB 贪心+排序
比较神奇的贪心 有点类似于田忌赛马. 如果我方最弱强于对面最弱,则直接最弱pk最弱. 如果我方最强强于对面最强,那么直接最强间pk. 否则,试着用我方最弱 pk 对方最强,看是否能打成平手. code ...
- 【洛谷P2664】 树上游戏 点分治
code: #include <bits/stdc++.h> #define N 200009 #define ll long long #define setIO(s) freopen( ...
- 2019.12.11 java程序中几种常见的异常以及出现此异常的原因
1.java.lang.NullpointerException(空指针异常) 原因:这个异常经常遇到,异常的原因是程序中有空指针,即程序中调用了未经初始化的对象或者是不存在的对象. 经常出现在创建对 ...
- Cesium 加载天地图
网上有很多 就是没说 加载天地图需要开发者秘钥,这个需要去天地图官网申请一个就可以了,下面贴上源码 还有就是Cesium也是需要token的哈 <!DOCTYPE html> <ht ...