중첩 목록 반복자 평면화
nestedList. 각 요소는 정수이거나 그 요소가 정수나 다른 목록일 수도 있는 목록입니다. 반복자를 구현하여 평면화하십시오.NestedIterator 클래스를 구현합니다.NestedIterator(List<NestedInteger> nestedList) 중첩 목록으로 반복자를 초기화합니다nestedList. int next() 중첩 목록에서 다음 정수를 반환합니다. boolean hasNext() 중첩된 목록에 여전히 일부 정수가 있으면 true를 반환하고 그렇지 않으면 false를 반환합니다. 코드는 다음 의사 코드로 테스트됩니다.
nestedList로 반복자 초기화
해상도 = []
iterator.hasNext() 동안
res 끝에 iterator.next()를 추가합니다.
해상도 반환
res가 예상 평면화 목록과 일치하면 코드가 올바른 것으로 판단됩니다.예 1:
입력: nestedList = [[1,1],2,[1,1]]
출력: [1,1,2,1,1]
설명: hasNext가 false를 반환할 때까지 next를 반복적으로 호출하면 next가 반환하는 요소의 순서는 [1,1,2,1,1]이어야 합니다.
예 2:
입력: nestedList = [1,[4,[6]]]
출력: [1,4,6]
설명: hasNext가 false를 반환할 때까지 next를 반복적으로 호출하면 next가 반환하는 요소의 순서는 [1,4,6]이어야 합니다.
제약:
1 <= nestedList.length <= 500 [-106, 106] 범위에 있습니다. 해결책:
# """
# 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.arr = []
self.expand(nestedList)
self.i = 0
def expand(self, nestedList):
for nl in nestedList:
if nl.isInteger():
self.arr += [nl.getInteger()]
else:
self.expand(nl.getList())
def next(self) -> int:
self.i += 1
return self.arr[self.i - 1]
def hasNext(self) -> bool:
return self.i < len(self.arr)
# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())
Reference
이 문제에 관하여(중첩 목록 반복자 평면화), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/theabbie/flatten-nested-list-iterator-7f2텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)