版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a786150017/article/details/85019289
341. Flatten Nested List Iterator
题目描述
给定一个嵌套的整数列表,用迭代器来flatten它。
每个元素要么是整数,要么是列表(同理,元素要么是整数,要么是其他列表)
例子
Example 1:
Input: [[1,1],2,[1,1]]
Output: [1,1,2,1,1]
Explanation: By calling next repeatedly until hasNext returns false,
the order of elements returned by next should be: [1,1,2,1,1].
Example 2:
Input: [1,[4,[6]]]
Output: [1,4,6]
Explanation: By calling next repeatedly until hasNext returns false,
the order of elements returned by next should be: [1,4,6].
思想
有点Trick的一道题…
(法1) 队列或栈来解决
(法2) 辅助空间,先把所有的整数存储起来(利用DFS)。
解法1
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger(object):
# def isInteger(self):
# """
# @return True if this NestedInteger holds a single integer, rather than a nested list.
# :rtype bool
# """
#
# def getInteger(self):
# """
# @return the single integer that this NestedInteger holds, if it holds a single integer
# Return None if this NestedInteger holds a nested list
# :rtype int
# """
#
# def getList(self):
# """
# @return the nested list that this NestedInteger holds, if it holds a nested list
# Return None if this NestedInteger holds a single integer
# :rtype List[NestedInteger]
# """
class NestedIterator(object):
def __init__(self, nestedList):
"""
Initialize your data structure here.
:type nestedList: List[NestedInteger]
"""
self.nestedList = nestedList
def next(self):
"""
:rtype: int
"""
if self.hasNext():
return self.nestedList.pop(0).getInteger()
def hasNext(self):
"""
:rtype: bool
"""
while self.nestedList:
if self.nestedList[0].isInteger():
return True
self.nestedList = self.nestedList[0].getList() + self.nestedList[1:]
return False
# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())
解法2
class NestedIterator(object):
def __init__(self, nestedList):
"""
Initialize your data structure here.
:type nestedList: List[NestedInteger]
"""
self.flatten = []
self.dfs(nestedList)
def dfs(self, nestedList):
for x in nestedList:
if x.isInteger():
self.flatten.append(x.getInteger())
else:
self.dfs(x.getList())
def next(self):
"""
:rtype: int
"""
return self.flatten.pop(0)
def hasNext(self):
"""
:rtype: bool
"""
return self.flatten