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

本文介绍了如何实现一个扁平化嵌套整数列表的迭代器,利用递归和双端队列(deque)数据结构。在LeetCode的题目中,给定一个包含嵌套整数的列表,要求实现一个迭代器,能顺序地返回所有整数。解题思路是通过递归遍历嵌套列表,将整数入队,当需要下一个整数时,从队头取出。代码实现了NestedIterator类,包括构造函数、next()和hasNext()方法,满足了迭代器的需求。
摘要由CSDN通过智能技术生成

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

原始题目链接:https://leetcode.cn/problems/flatten-nested-list-iterator/

给你一个嵌套的整数列表 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 与预期的扁平化列表匹配,那么你的代码将会被判为正确。

在这里插入图片描述

解题思路:

递归的方法比较简单,因为是有嵌套的列表存在,所以想到使用递归的方法,使用一个双端队列的数据结构,出队操作是获取队头的元素,入队从队尾入队。

代码实现:

# """
# 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 dfs(self, nest_list):
        for nest in nest_list:
            # 如果当前是整数,直接将数字加入队列
            if nest.isInteger():
                self.queue.append(nest.getInteger())
            # 如果是列表,递归调用
            else:
                self.dfs(nest.getList())


    def __init__(self, nestedList: [NestedInteger]):
        # 初始化一个双端队列用于存储嵌套列表扁平化后的结果
        self.queue = collections.deque()
        # 调用扁平化处理函数
        self.dfs(nestedList)
    
    def next(self) -> int:
       # 出队操作,即获得元素,要取得先入队的元素,即队头
       return self.queue.popleft()

        
    
    def hasNext(self) -> bool:
        # 判断是否还有元素,判断当前队列长度是否还大于0即可
        return len(self.queue) > 0
         

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

参考文献:
https://leetcode.cn/problems/flatten-nested-list-iterator/solution/fu-xue-ming-zhu-xiang-jie-ti-yi-shu-li-d-n4qa/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值