Loading...

10-20 leetcode 0341

链接 341. Flatten Nested List Iterator

题目

You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.

Implement the NestedIterator class:

  • NestedIterator(List nestedList) Initializes the iterator with the nested list nestedList.
  • int next() Returns the next integer in the nested list.
  • boolean hasNext() Returns true if there are still some integers in the nested list and false otherwise.

题解

就其实直接按照题意遍历就行了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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) -> list["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: list[NestedInteger]):
self._data = nestedList

def next(self) -> int:
return self._data.pop(0).getInteger()

def hasNext(self) -> bool:
while self._data:
if self._data[0].isInteger():
return True
self._data = self._data[0].getList() + self._data[1:]
return False

Comment