• 模拟卷Leetcode【普通】341. 扁平化嵌套列表迭代器


    汇总:模拟卷Leetcode 题解汇总

    341. 扁平化嵌套列表迭代器

    给你一个嵌套的整数列表 nestedList 。每个元素要么是一个整数,要么是一个列表;该列表的元素也可能是整数或者是其他列表。请你实现一个迭代器将其扁平化,使之能够遍历这个列表中的所有整数。

    实现扁平迭代器类 NestedIterator :

    NestedIterator(List nestedList) 用嵌套列表 nestedList 初始化迭代器。
    int next() 返回嵌套列表的下一个整数。
    boolean hasNext() 如果仍然存在待迭代的整数,返回 true ;否则,返回 false 。
    你的代码将会用下述伪代码检测:

    initialize iterator with nestedList
    res = []
    while iterator.hasNext()
    append iterator.next() to the end of res
    return res
    如果 res 与预期的扁平化列表匹配,那么你的代码将会被判为正确。

    示例 1:

    输入:nestedList = [[1,1],2,[1,1]]
    输出:[1,1,2,1,1]
    解释:通过重复调用 next 直到 hasNext 返回 false,next 返回的元素的顺序应该是: [1,1,2,1,1]。
    示例 2:

    输入:nestedList = [1,[4,[6]]]
    输出:[1,4,6]
    解释:通过重复调用 next 直到 hasNext 返回 false,next 返回的元素的顺序应该是: [1,4,6]。

    提示:

    1 <= nestedList.length <= 500
    嵌套列表中的整数值在范围 [-106, 106] 内

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/flatten-nested-list-iterator
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    代码:

    from leetcode_python.utils import *
    
    
    # """
    # This is the interface that allows for creating nested lists.
    # You should not implement it, or speculate about its implementation
    # """
    class NestedInteger:
       def isInteger(self) -> bool:
           """
           @return True if this NestedInteger holds a single integer, rather than a nested list.
           """
           pass
    
       def getInteger(self) -> int:
           """
           @return the single integer that this NestedInteger holds, if it holds a single integer
           Return None if this NestedInteger holds a nested list
           """
           pass
    
       def getList(self) -> [NestedInteger]:
           """
           @return the nested list that this NestedInteger holds, if it holds a nested list
           Return None if this NestedInteger holds a single integer
           """
           pass
    
    class NestedIterator:
        def __init__(self, nestedList: [NestedInteger]):
            def dfs(nestedList: [NestedInteger]):
                res = []
                for x in nestedList:
                    if x.isInteger():res.append(x.getInteger())
                    else:res.extend(dfs(x.getList()))
                return res
            self.nums = dfs(nestedList)
    
        def next(self) -> int:
            return self.nums.pop(0)
    
        def hasNext(self) -> bool:
            return len(self.nums)>0
    
    
    # Your NestedIterator object will be instantiated and called as such:
    # i, v = NestedIterator(nestedList), []
    # while i.hasNext(): v.append(i.next())
    
    
    def test(data_test):
        s = Solution()
        data = data_test    # normal
        # data = [List2Node(data_test[0])]  # list转node
        return s.getResult(*data)
    
    def test_obj(data_test):
        result = [None]
        obj = Solution(*data_test[1][0])
        for fun,data in zip(data_test[0][1::],data_test[1][1::]):
            if data:
                res = obj.__getattribute__(fun)(*data)
            else:
                res = obj.__getattribute__(fun)()
            result.append(res)
        return result
    
    if __name__ == '__main__':
        datas = [
            [],
        ]
        for data_test in datas:
            t0 = time.time()
            print('-'*50)
            print('input:', data_test)
            print('output:', test(data_test))
            print(f'use time:{time.time() - t0}s')
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78

    备注:
    GitHub:https://github.com/monijuan/leetcode_python

    CSDN汇总:模拟卷Leetcode 题解汇总

    可以加QQ群交流:1092754609

    leetcode_python.utils详见汇总页说明
    先刷的题,之后用脚本生成的blog,如果有错请留言,我看到了会修改的!谢谢!

  • 相关阅读:
    【毕业设计】口罩佩戴检测系统 - opencv 卷积神经网络 机器视觉 深度学习
    【爬虫系列】Python爬虫实战--招聘网站的职位信息爬取
    【593. 有效的正方形】
    文心一言 VS 讯飞星火 VS chatgpt (113)-- 算法导论10.2 5题
    鸿蒙开发-HarmonyOS UI架构
    【AIGC】百度文库文档助手之 - 一键生成PPT
    微软推出 Hierarchical Transformer 实现更高准确率的语音评测
    Gin 笔记(04)— 自定义 HTTP 配置、使用 HTTP 方法、自定义请求 url 不存在时的返回值、自定义重定向
    80. 删除有序数组中的重复项 II
    学习 Axure RP 的不同阶段
  • 原文地址:https://blog.csdn.net/qq_34451909/article/details/127609386