← 返回 airbnb 的题目列表Nested List Iterator with Remove
类型:online_judge
Implement a Nested List Iterator with remove()
Implement a Python iterator over a two-dimensional list of integers. Traverse the outer list from top to bottom and each inner list from left to right.
class NestedListIterator:
def __init__(self, data: list[list[int]]):
...
def hasNext(self) -> bool:
...
def next(self) -> int:
...
def remove(self) -> None:
...
Method requirements
hasNext(): Return True if there is another integer after the current cursor; otherwise return False. It may be called repeatedly and must not change the result of a subsequent next() call.
next(): Return the next integer in traversal order.
Raise an exception if no integers remain.
remove(): Remove from the original nested-list object the element returned by the most recent successful next() call.
At most one remove() call is allowed after each successful next().
Calling remove() before any next(), or calling it twice after the same next(), must raise an exception.
Example
data = [[], [1, 2, 3], [4, 5], [], [], [6], [7, 8], [], [9], [10], []]
it = NestedListIterator(data)
Successive calls to next() return:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
For the following input:
data = [[], [1, 2, 3], [4, 5]]
it = NestedListIterator(data)
it.next() # 1
it.next() # 2
it.remove()
After remove(), data must become:
[[], [1, 3], [4, 5]]
The next call to next() must return 3, not skip it.
Constraints
data is a two-dimensional list of integers; inner lists may be empty.
remove() must mutate the supplied data in place rather than a copy.
Let R be the number of inner lists and N the total number of integers.
Except for shifts caused by remove(), assume the input is not modified externally during iteration.
Example
Input
data = [[], [1, 2, 3], [4, 5]]; operations = ["next", "next", "remove", "next", "next", "next"]
Output
returns = [1, 2, null, 3, 4, 5]; final_data = [[], [1, 3], [4, 5]]