美文网首页
leetcode 扁平化嵌套列表迭代器 python 之双向队列

leetcode 扁平化嵌套列表迭代器 python 之双向队列

作者: DaydayHoliday | 来源:发表于2019-03-29 12:13 被阅读0次

看了网上的评论,看来这题标准地来是需要用栈的。思想的话基本也是教科书级。但那样的话,在初始化的时候实际上就把结果生成了。这似乎就失去了构造迭代器的意义。(即,迭代器的话更加希望我边取边算,这样会更快,尤其是我只要前k个而不是全部的场景下;不过这个题目让全部取出来,就体现不出迭代器的优势)。而我的思路则是构造一个随取随算的双向队列。

import collections
class NestedIterator(object):

    def __init__(self, nestedList):
        """
        Initialize your data structure here.
        :type nestedList: List[NestedInteger]
        """
        self.d=collections.deque()
        for n_list in nestedList:
            self.d.append(n_list)

    def next(self):
        """
        :rtype: int
        """
        while True:
            l=self.d.popleft()
            if l.isInteger():
                return l.getInteger()
            for n_list in l.getList()[::-1]:
                self.d.appendleft(n_list)
        
        

    def hasNext(self):
        """
        :rtype: bool
        """
        def truelist(di):
            if di.isInteger():
                return True
            if len(di.getList())==0:
                return False
            for dii in di.getList():
                if truelist(dii):
                    return True
            return False
            
        if len(self.d)==0:
            return False
        for di in self.d:
            if truelist(di):
                return True
        return False

init被彻底简化;next也不复杂;hasNext代码稍显复杂,但其实运行效率应该也还可以。

相关文章

网友评论

      本文标题:leetcode 扁平化嵌套列表迭代器 python 之双向队列

      本文链接:https://www.haomeiwen.com/subject/dgclbqtx.html