作者: 负雪明烛
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. EXCEL-批量下拉填充

    3.批量下拉填充  =>    全选->Ctrl+G定位空值->随意找一个空白单元格输入=还有此单元格想要填充的内容->按Ctrl+Enter,等待几秒,即可,批量下拉填充:

  2. Tomcat类加载机制和JAVA类加载机制的比较

    图解Tomcat类加载机制    说到本篇的tomcat类加载机制,不得不说翻译学习tomcat的初衷.    之前实习的时候学习javaMelody的源码,但是它是一个Maven的项目,与我们自己的 ...

  3. flink03-----1.Task的划分 2.共享资源槽 3.flink的容错

    1. Task的划分 在flink中,划分task的依据是发生shuffle(也叫redistrubute),或者是并行度发生变化 1.  wordcount为例 package cn._51doit ...

  4. 零基础学习java------40---------Maven(maven的概念,安装,maven在eclipse中使用),springboot(spring整合springmvc(注解),spring整合mybatis(常见的配置文件)),前端页面(bootstrap软件)

    一 maven 1. Maven的相关概念 1.1 项目开发中遇到的问题 (1)都是同样的代码,为什么在我的机器上可以编译执行,而在他的机器上就不行? (2)为什么在我的机器上可以正常打包,而配置管理 ...

  5. keil 报错 expected an identifier

    该报错是因为命名重复,可能是因为你加的头文件里面的命名和原程序中的有重复,所以产生了错误.

  6. Android项目的settings.gradle和build.gradle

    gradle构建的项目中的build.gradle和settings.gradle文件 build.gradle 浅析(一) 史上最全的Android build.gradle配置教程 Android ...

  7. nexus 私服 拉不了 jar 包,报 Not authorized

    问题: 无法下载导入jar包,idea reload 时 报: Could not transfer artifact com.xxx:parent:pom:1.0-SNAPSHOT from/to ...

  8. 【Java 基础】Java 根据Class获取对象实例

    Spring在代码中获取bean的几种方式 方法一:在初始化时保存ApplicationContext对象 方法二:通过Spring提供的utils类获取ApplicationContext对象 方法 ...

  9. mybatis联合查询

    1.有学生实体 @Component @Scope("prototype") public class StudentInfo { private Integer studentI ...

  10. 【科研】科研【合同】盖章流程/横向·非涉密/电子科技大学

    [前置手续] 一.在科研管理系统里填单子,立项. 二.科研管理系统审核通过后,对于对面给好的合同,在合同系统里选择[合同业务发起-发起非标准合同],填单子. 三.会有一系列的审核,审核完成后打印合同备 ...