我试图通过Leetcode上的在线判断来解决问题。问题是:给定一个嵌套的整数列表,实现一个迭代器来展平它。
每个元素都是整数或列表 - 其元素也可以是整数或其他列表。
示例1: 给出列表[[1,1],2,[1,1]],
通过反复调用next直到hasNext返回false,next返回的元素的顺序应为:[1,1,2,1,1]
完整的问题是here。
问题表明它将实例化使用以下代码实现的类:
# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())
以下是我的解决方案:
class NestedIterator(object):
currIdx = 0
def __init__(self, nestedList):
"""
Initialize your data structure here.
:type nestedList: List[NestedInteger]
"""
newFlattenedList = []
self.flattenList(nestedList, newFlattenedList)
nestedList = newFlattenedList
self.flattenedList = nestedList
def flattenList(self, nestedList, flattenedList):
for ele in nestedList:
if type(ele) == list and ele > 0:
self.flattenList(ele, flattenedList)
else:
flattenedList.append(ele)
return
def next(self):
"""
:rtype: int
"""
if self.hasNext():
test = self.flattenedList[self.currIdx]
self.currIdx +=1
return test
else:
return NULL
def hasNext(self):
"""
:rtype: bool
"""
nextIdx = self.currIdx + 1
return True if nextIdx <= len(self.flattenedList) else False
当我在输入[[1,1],2,[1,1]]的IDE中运行此代码时,我得到[1,1,2,1,1]的输出。出于某种原因,当我使用在线判断运行代码时,给定输入[[1,1],2,[1,1]],输出为[[1,1],2,[1,1] ]被退回。为什么leetcode在线判断返回不同的东西?
答案 0 :(得分:1)
您的意思是None
而不是NULL
对吗?
def next(self):
"""
:rtype: int
"""
if self.hasNext():
test = self.flattenedList[self.currIdx]
self.currIdx +=1
return test
else:
#return NULL
return None
通过运行:
nestedList = [[1,1],2,[1,1]]
i, v = NestedIterator(nestedList), []
while i.hasNext(): v.append(i.next())
print v
我得到了:
[1, 1, 2, 1, 1]
所以,除了将NULL更改为None之外,我都不知道。
答案 1 :(得分:1)
您的解决方案有两个问题。
这是修改后的代码。这应该在任何地方运行。
class NestedIterator(object):
currIdx = 0
def __init__(self, nestedList):
"""
Initialize your data structure here.
:type nestedList: List[NestedInteger]
"""
newFlattenedList = []
self.flattenList(nestedList, newFlattenedList)
nestedList = newFlattenedList
self.flattenedList = nestedList
def flattenList(self, nestedList, flattenedList):
for ele in nestedList:
if type(ele) == list and len(ele) > 0:
self.flattenList(ele, flattenedList)
else:
flattenedList.append(ele)
return
def next(self):
"""
:rtype: int
"""
if self.hasNext():
test = self.flattenedList[self.currIdx]
self.currIdx +=1
return test
else:
return None
def hasNext(self):
"""
:rtype: bool
"""
nextIdx = self.currIdx + 1
return True if nextIdx <= len(self.flattenedList) else False