zoukankan      html  css  js  c++  java
  • 边工作边刷题:70天一遍leetcode: day 56-1

    Peeking Iterator

    要点:想成cache会比较容易理解,要进一步要考虑什么时候put to cache和什么时候invalidate cache,

    • put to cache:peek的时候,如果没在cache中,因为iterator已经移动,直到下一次next,都要在cache中找。
    • invalidate cache:next的时候如果在cache中,返回cache同时要invalidate,因为之后无论call peek or next都是要找到当前的下一个值,当前值没用了。

    错误点:

    • 在peek里call了2次iterator.next(),put to cache的时候call一次就够了
    # 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.cache = None
    
        def peek(self):
            """
            Returns the next element in the iteration without advancing the iterator.
            :rtype: int
            """
            if not self.cache:
                self.cache = self.iterator.next()
                # self.iterator.next()
            return self.cache
    
        def next(self):
            """
            :rtype: int
            """
            if self.cache:
                ret = self.cache
                self.cache = None
                return ret
    
            return self.iterator.next()
            
    
        def hasNext(self):
            """
            :rtype: bool
            """
            return self.cache is not None or 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].
    
    
  • 相关阅读:
    IEnumerable、ICollection、IList、List关系和区别
    在Winform界面中使用DevExpress的TreeList实现节点过滤查询的两种方式
    关键字Lock的简单小例子
    .NET Core DI简单介绍
    Linux服务器部署.Net Core笔记:六、安装MySQL
    表的透视变换
    ZedGraph怎样在生成曲线时随机生成不一样的颜色
    3、手写Unity容器--第N层依赖注入
    微信支付-小程序H5 公众号 Payment SDK
    WPF继续响应被标记为已处理事件的方法
  • 原文地址:https://www.cnblogs.com/absolute/p/5690321.html
Copyright © 2011-2022 走看看