LeetCode 284 Peeking Iterator (Python)

Posted by 小明MaxMing on February 8, 2021

题目

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().

解题思路

记录当前的peek,next会返回当前的peek,并且更新peek为下一个数

代码

class PeekingIterator:
    def __init__(self, iterator):
        """
        Initialize your data structure here.
        :type iterator: Iterator
        """
        self.it = iterator
        self.peeknum = self.it.next() if self.it.hasNext() else None

    def peek(self):
        """
        Returns the next element in the iteration without advancing the iterator.
        :rtype: int
        """
        return self.peeknum

    def next(self):
        """
        :rtype: int
        """
        ret = self.peeknum
        self.peeknum = self.it.next() if self.it.hasNext() else None
        return ret

    def hasNext(self):
        """
        :rtype: bool
        """
        return self.peeknum is not None

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅