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

本文详细解析了LeetCode的341题——扁平化嵌套列表迭代器的解题思路,包括如何通过遍历和递归方法将嵌套列表转化为普通列表。代码实现部分展示了一个利用递归实现的NestedIterator类,该类能够依次返回嵌套列表中的所有整数。在遇到嵌套列表时,递归调用自身以处理子列表。参考文献提供了进一步的解题思路和解析。
摘要由CSDN通过智能技术生成


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

题目描述

在这里插入图片描述

解题思路

  • 方法一:
    遍历所有元素,存在列表中。这种方法不是最优解。

代码实现

# """
# 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.
#        """
#
#    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
#        """
#
#    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
#        """

class NestedIterator:
    def __init__(self, nestedList: [NestedInteger]):
        self.arr = []

        def dfs(nests):
            for ele in nests:
                if ele.isInteger():
                    self.arr.append(ele.getInteger())
                else:
                    dfs(ele.getList())
        
        dfs(nestedList)
        
    def next(self) -> int:
        return self.arr.pop(0)
    
    def hasNext(self) -> bool:
        return len(self.arr)


# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())

参考文献

负雪明烛】详解题意,梳理递归和迭代两种思路

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值