Flatten 2D Vector
此题只需要两个指针就能搞定了,但是实际上的思路还是lazy iteration,也就是需要的时候我才往前走,不要的时候就赖在原地不停给结果,其实这也是所有迭代器类型的题目的思路,能不先遍历就尽量先不遍历,一旦遍历了就一次性多存储一些数,这道题还需要注意空列表的情况
class Vector2D(object):
def __init__(self, vec2d):
"""
Initialize your data structure here.
:type vec2d: List[List[int]]
"""
self.n = len(vec2d)
self.vector = vec2d
self.curRow = 0
self.curCol = 0
def next(self):
"""
:rtype: int
"""
result = self.vector[self.curRow][self.curCol]
self.curCol += 1
return result
def hasNext(self):
"""
:rtype: bool
"""
while self.curRow < self.n and self.curCol >= len(self.vector[self.curRow]):
self.curRow += 1
self.curCol = 0
return self.curRow < self.n
# Your Vector2D object will be instantiated and called as such:
# i, v = Vector2D(vec2d), []
# while i.hasNext(): v.append(i.next())