题目来源:
https://leetcode.com/problems/flatten-nested-list-iterator/submissions/
自我感觉难度/真实难度:mid 写题时间时长:
题意:
分析:
自己的代码:
class NestedIterator(object): def __init__(self, nestedList): """ Initialize your data structure here. :type nestedList: List[NestedInteger] """ self.queue=collections.deque() def getAll(nests): for nest in nests: if nest.isInteger(): self.queue.append(nest.getInteger()) else: getAll(nest.getList()) getAll(nestedList) def next(self): """ :rtype: int """ if self.hasNext(): return self.queue.popleft() else: return None def hasNext(self): """ :rtype: bool """ return len(self.queue)
代码效率/结果:
优秀代码:
class NestedIterator(object): def __init__(self, nestedList): """ Initialize your data structure here. :type nestedList: List[NestedInteger] """ # print nestedList self.stack = nestedList # print "----", self.stack self.stack.reverse() def next(self): """ :rtype: int """ return self.stack.pop().getInteger() def hasNext(self): """ :rtype: bool """ while self.stack and not self.stack[-1].isInteger(): lst = self.stack.pop().getList() if lst: lst.reverse() self.stack.extend(lst) return len(self.stack) != 0
代码效率/结果:
自己优化后的代码:
反思改进策略:
1.不会使用类变量。 solution 类里面,使用self.queue,那么在整个类里面都是可以使用的
2.pop() 默认是弹出后面的元素,popleft(),弹出 左边的
3.没有很明白下面两个函数是什么用处:
getList()
.getInteger()