선발대

[스파르타] 99클럽 2기 코테스터디 35일차 TIL / leet 341 본문

스파르타코딩클럽/활동 내용

[스파르타] 99클럽 2기 코테스터디 35일차 TIL / leet 341

신선한 스타트 2024. 6. 23. 23:46

Leetcode: 341. Flatten Nested List Iterator (링크)

 

341. Flatten Nested List Iterator

 

# """
# 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 process_element(self, element):
        if element.isInteger():
            return [element.getInteger()]
        element_results = []
        for element_local in element.getList():
            element_results += self.process_element(element_local)
        return element_results

    def __init__(self, nestedList: [NestedInteger]):
        self.curr_list = []
        for element in nestedList:
            self.curr_list += self.process_element(element)
        self.idx = 0
    
    def next(self) -> int:
        element = self.curr_list[self.idx]
        self.idx += 1
        return element
    
    def hasNext(self) -> bool:
        return self.idx < len(self.curr_list)
         

# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())

오늘 미들러 풀이 끝!


참고한 풀이: https://leetcode.com/problems/flatten-nested-list-iterator/solutions/4187860/easiest-solution-in-python/

 

Comments