您的位置:首页 > 编程语言 > Python开发

[LeetCode][Python]Flatten Nested List Iterator

2016-05-13 16:23 585 查看

Flatten Nested List Iterator

Given a nested list of integers, implement an iterator to flatten it.

Each element is either an integer, or a list -- whose elements may also be integers or other lists.

Example 1:
Given the list
[[1,1],2,[1,1]]
,

By calling next repeatedly until hasNext returns false, the order of elements returned by next should be:
[1,1,2,1,1]
.

Example 2:
Given the list
[1,[4,[6]]]
,

By calling next repeatedly until hasNext returns false, the order of elements returned by next should be:
[1,4,6]
.

https://leetcode.com/problems/flatten-nested-list-iterator/

展平嵌套的list。

从调用的方式来看,总会调用到最后,所以在构造函数中递归展开所有的数放到一位数组中。

另一种方式是把nested list压到栈中,需要的时候再从栈中拿。

注意需要调用注释中的isInteger(),getInteger()和getList()三个方法。

# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger(object):
#    def isInteger(self):
#        """
#        @return True if this NestedInteger holds a single integer, rather than a nested list.
#        :rtype bool
#        """
#
#    def getInteger(self):
#        """
#        @return the single integer that this NestedInteger holds, if it holds a single integer
#        Return None if this NestedInteger holds a nested list
#        :rtype int
#        """
#
#    def getList(self):
#        """
#        @return the nested list that this NestedInteger holds, if it holds a nested list
#        Return None if this NestedInteger holds a single integer
#        :rtype List[NestedInteger]
#        """
class NestedIterator(object):

def __init__(self, nestedList):
"""
Initialize your data structure here.
:type nestedList: List[NestedInteger]
"""
self.__list = []
self.__index = 0
self.__getList(nestedList)

def __getList(self, nestedList):
for item in nestedList:
if item.isInteger():
self.__list.append(item.getInteger())
else:
self.__getList(item.getList())

def next(self):
"""
:rtype: int
"""
res = self.__list[self.__index]
self.__index += 1
return res

def hasNext(self):
"""
:rtype: bool
"""
if(self.__index < len(self.__list)):
return True
return False
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: