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

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

Difficulty: 中等

给你一个嵌套的整型列表。请你设计一个迭代器,使其能够遍历这个整型列表中的所有整数。

列表中的每一项或者为一个整数,或者是另一个列表。其中列表的元素也可能是整数或是其他列表。

示例 1:

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

示例 2:

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

Solution

思路如下:对于给定的整型列表,首先把里面的所有元素全部取出来放到一个栈里面,比如整型列表为[[1,2], 3, [4,5]],放到栈里面那么得到的是[[4,5], 3, [1,2]],然后再判断栈顶元素,当栈顶非空并且不是整数,则需要从栈顶pop出来的嵌套整型取出它包含的所有元素,直到栈顶为空或者栈顶已经是整数了,那么此时便可以调用next返回整数。

# """
# 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.stack = []
        for i in range(len(nestedList)-1, -1, -1):
            self.stack.append(nestedList[i])
    
    def next(self) -> int:
        return self.stack.pop().getInteger()
        
    def hasNext(self) -> bool:
        # 取出栈顶的元素,当栈非空并且不是整型,需要把它们从嵌套的整型里面拿出来
        while self.stack and not self.stack[-1].isInteger():
            tmp = self.stack.pop()
            data = tmp.getList()
            for i in range(len(data)-1, -1, -1):
                self.stack.append(data[i])
        # 如果此时栈里面已经没有元素了,那么说明已经没有元素可以迭代了,返回False
        return False if not self.stack else True
        
​
# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())
posted @ 2021-03-23 23:30  swordspoet  阅读(27)  评论(0编辑  收藏  举报