我想让我的解决方案通过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
当我在IDE中用输入[[1,1],2,[1,1]]运行这段代码时,得到的输出是[1,1,2,1,1]。出于某种原因,当我使用online judge运行代码时,给定输入[[1,1],2,[1,1]],输出是[[1,1],返回2,[1,1]]。为什么leetcode在线评委会返回不同的结果?你知道吗
你的解决方案有两个问题。你知道吗
这是修改后的代码。应该到处都是。你知道吗
你是说
None
不是NULL
对吧?你知道吗通过运行:
我得到了:
所以,除了把NULL改成None,我不知道。你知道吗
相关问题 更多 >
编程相关推荐