Given a nested list of integers, implement an iterator to flatten it.git
Each element is either an integer, or a list -- whose elements may also be integers or other lists.github
Example 1:數組
Input: [[1,1],2,[1,1]]
Output: [1,1,2,1,1]
Explanation: By calling next repeatedly until hasNext returns false,app
the order of elements returned by next should be: \[1,1,2,1,1].
Example 2:函數
Input: [1,[4,[6]]]
Output: [1,4,6]
Explanation: By calling next repeatedly until hasNext returns false,ui
the order of elements returned by next should be: \[1,4,6].
給定一個嵌套的整型列表。設計一個迭代器,使其可以遍歷這個整型列表中的全部整數。設計
列表中的項或者爲一個整數,或者是另外一個列表。code
示例 1:遞歸
輸入: [[1,1],2,[1,1]]
輸出: [1,1,2,1,1]
解釋: 經過重複調用 next 直到 hasNext 返回false,next 返回的元素的順序應該是: [1,1,2,1,1]。
示例 2:隊列
輸入: [1,[4,[6]]]
輸出: [1,4,6]
解釋: 經過重複調用 next 直到 hasNext 返回false,next 返回的元素的順序應該是: [1,4,6]。
# -*- coding: utf-8 -*- # @Author: 何睿 # @Create Date: 2019-04-08 14:01:53 # @Last Modified by: 何睿 # @Last Modified time: 2019-04-08 14:45:23 from collections import deque class NestedIterator(object): def __init__(self, nestedList): """ Initialize your data structure here. :type nestedList: List[NestedInteger] """ self.queue = deque() # 遍歷獲得全部的元素 self._get_elements(nestedList) # 統計元素的個數 self.count = len(self.queue) def _get_elements(self, nestedList): for item in nestedList: # isInteger 方法是 NestedIterator 類提供的方法 # 若是是整型,將該數組添加到雙端隊列中 if item.isInteger(): self.queue.append(item.getInteger()) # 若是是一個 List ,遞歸調用 _get_elements else: self._get_elements(item.getList()) return def next(self): """ :rtype: int """ hasnext = self.hasNext() if hasnext: self.count -= 1 # 返回下一個元素 return self.queue.popleft() return False def hasNext(self): """ :rtype: bool """ return self.count > 0