作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/peeking-iterator/description/

题目描述:

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.

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

题目大意

已有一个迭代器,这个迭代器里面有hasNext()next()函数,让我们对这个迭代器进行封装,添加一个能获取下一个元素是什么但不需要弹出的peek()函数。

解题方法

这个题可以说非常简单没难度了,peek()通过获取迭代器的next()然后保存当前值就好了。如果调用自身的next()的时候,需要判断一下当前的值是否存在,如果存在就优先弹出。hasNext()也是同样的道理。

需要注意的两点:第一,刚开始把保存下一个元素的变量定义为了self.next,这样和函数重名了是不可以的;第二,注意保存的是int,因此注意不能给self.n初始化任何一个整数值,使用None判断是否保存有元素,if的时候不能简单的if self.n这种操作,因为当n等于0的时候也会触发。

每个操作的时间复杂度是O(1),空间复杂度是O(1).

代码如下:

# Below is the interface for Iterator, which is already defined for you.
#
# class Iterator(object):
# def __init__(self, nums):
# """
# Initializes an iterator object to the beginning of a list.
# :type nums: List[int]
# """
#
# def hasNext(self):
# """
# Returns true if the iteration has more elements.
# :rtype: bool
# """
#
# def next(self):
# """
# Returns the next element in the iteration.
# :rtype: int
# """ class PeekingIterator(object):
def __init__(self, iterator):
"""
Initialize your data structure here.
:type iterator: Iterator
"""
self.iterator = iterator
self.n = None def peek(self):
"""
Returns the next element in the iteration without advancing the iterator.
:rtype: int
"""
if self.n == None:
self.n = self.iterator.next()
return self.n def next(self):
"""
:rtype: int
"""
if self.n != None:
tmp = self.n
self.n = None
return tmp
else:
return self.iterator.next() def hasNext(self):
"""
:rtype: bool
"""
if self.n != None:
return True
else:
return self.iterator.hasNext() # Your PeekingIterator object will be instantiated and called as such:
# iter = PeekingIterator(Iterator(nums))
# while iter.hasNext():
# val = iter.peek() # Get the next element but not advance the iterator.
# iter.next() # Should return the same value as [val].

参考资料:

日期

2018 年 9 月 26 日 —— 美好的一周又快要过去了。。

【LeetCode】284. Peeking Iterator 解题报告(Python)的更多相关文章

  1. 【LeetCode】341. Flatten Nested List Iterator 解题报告(Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归+队列 栈 日期 题目地址:https://lee ...

  2. [LeetCode] 284. Peeking Iterator 瞥一眼迭代器

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

  3. 【LeetCode】120. Triangle 解题报告(Python)

    [LeetCode]120. Triangle 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址htt ...

  4. LeetCode 1 Two Sum 解题报告

    LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...

  5. 【LeetCode】Permutations II 解题报告

    [题目] Given a collection of numbers that might contain duplicates, return all possible unique permuta ...

  6. 【LeetCode】Island Perimeter 解题报告

    [LeetCode]Island Perimeter 解题报告 [LeetCode] https://leetcode.com/problems/island-perimeter/ Total Acc ...

  7. 【LeetCode】01 Matrix 解题报告

    [LeetCode]01 Matrix 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/01-matrix/#/descripti ...

  8. 【LeetCode】Largest Number 解题报告

    [LeetCode]Largest Number 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/largest-number/# ...

  9. 【LeetCode】Gas Station 解题报告

    [LeetCode]Gas Station 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/gas-station/#/descr ...

随机推荐

  1. R语言hist重叠图作法

    set.seed(1) h1<-hist(rnorm(1000,100,5)) h2<-hist(rnorm(1000,99,5)) plot(h2,col=rgb(255,0,0,50, ...

  2. jumpserver——脚本安装

    CentOS Linux release 7.7.1908 (Core) 3.10.0-1062.4.1.el7.x86_64 Initialize(){ yum update -y systemct ...

  3. 学习java 7.19

    学习内容: 接口的组成中加入了默认方法,静态方法,私有方法 接口中默认方法:public default 返回值类型  方法名(参数列表){ } public default void show()  ...

  4. 带你全面了解 OAuth2.0

    最开始接触 OAuth2.0 的时候,经常将它和 SSO单点登录搞混.后来因为工作需要,在项目中实现了一套SSO,通过对SSO的逐渐了解,也把它和OAuth2.0区分开了.所以当时自己也整理了一篇文章 ...

  5. Learning Spark中文版--第六章--Spark高级编程(1)

    Introduction(介绍) 本章介绍了之前章节没有涵盖的高级Spark编程特性.我们介绍两种类型的共享变量:用来聚合信息的累加器和能有效分配较大值的广播变量.基于对RDD现有的transform ...

  6. Spark(七)【RDD的持久化Cache和CheckPoint】

    RDD的持久化 1. RDD Cache缓存 ​ RDD通过Cache或者Persist方法将前面的计算结果缓存,默认情况下会把数据以缓存在JVM的堆内存中.但是并不是这两个方法被调用时立即缓存,而是 ...

  7. Flume(四)【配置文件总结】

    目录 一.Agent 二.Source taildir arvo netstat exec spooldir 三.Sink hdfs kafka(待续) hbase(待续) arvo logger 本 ...

  8. netty系列之:手持framecodec神器,创建多路复用http2客户端

    目录 简介 配置SslContext 客户端的handler 使用Http2FrameCodec Http2MultiplexHandler和Http2MultiplexCodec 使用子channe ...

  9. 【JAVA开发】浅析双亲委派机制

    双亲委派机制存在的意义 双亲委派只是一种说法,个人觉得叫单亲委派更合适,因为向上传递的父类只有一个,估计只是翻译过来的,形成的一种习惯,大家可以当做单亲委派 四种加载器都是用于类的加载,只是加载的对象 ...

  10. 容器之分类与各种测试(四)——map

    map和set的区别在于,前者key和value是分开的,前者的key不会重复,value可以重复:后者的key即为value,后者的value不允许重复.还有,map在插入时可以使用 [ ]进行(看 ...