341. Flatten Nested List Iterator
Read the full problem statement on LeetCode.
Difficulty: medium Acceptance: 65% Topics: Stack, Tree, Depth-First Search, Design, Queue, Iterator
View full problem on LeetCode Reference solution (spoiler · python)
# Time: O(n), n is the number of the integers.
# Space: O(h), h is the depth of the nested lists.
class NestedIterator(object):
def __init__(self, nestedList):
"""
Initialize your data structure here.
:type nestedList: List[NestedInteger]
"""
self.__depth = [[nestedList, 0]]
def next(self):
"""
:rtype: int
"""
nestedList, i = self.__depth[-1]
self.__depth[-1][1] += 1
return nestedList[i].getInteger()
def hasNext(self):
"""
:rtype: bool
"""
while self.__depth:
nestedList, i = self.__depth[-1]
if i == len(nestedList):
self.__depth.pop()
elif nestedList[i].isInteger():
return True
else:
self.__depth[-1][1] += 1
self.__depth.append([nestedList[i].getList(), 0])
return False
Solution from kamyu104/LeetCode-Solutions · MIT
Similar questions