Zigzag Iterator
这道题主要注意列指针跳的时候的情况,另外也可以用generator来实现,但是个人觉得用迭代器实现迭代器其实算作弊了,不符合出题者的意图
class ZigzagIterator(object):
def __init__(self, v1, v2):
"""
Initialize your data structure here.
:type v1: List[int]
:type v2: List[int]
"""
self.nestedVector = [v1, v2]
self.curRow = 0
self.curCol = 0
def next(self):
"""
:rtype: int
"""
result = self.nestedVector[self.curRow][self.curCol]
if self.curRow:
self.curCol += 1
self.curRow = 0
else:
self.curRow += 1
return result
def hasNext(self):
"""
:rtype: bool
"""
if self.curCol >= len(self.nestedVector[self.curRow]):
if self.curRow:
self.curRow = 0
self.curCol += 1
else:
self.curRow = 1
return self.curCol < len(self.nestedVector[self.curRow])
# Your ZigzagIterator object will be instantiated and called as such:
# i, v = ZigzagIterator(v1, v2), []
# while i.hasNext(): v.append(i.next())