边工作边刷题:70天一遍leetcode: day 85-3
Zigzag Iterator
要点:
- 实际不是zigzag而是纵向访问
- 这题可以扩展到k个list,也可以扩展到只给iterator而不给list。结构上没什么区别,iterator的hasNext和计数殊途同归。
- 一种方法利用queue,进queue的顺序就是下一个要访问的元素index和v,实际就是level order traversal
- 另一种是用一个list存每个v的当前位置(or iterator)。然后track count:当前列访问完了(即list访问一遍),reset count,而如果一列元素没了,就把当前的v从list中去掉。
- 两种方法其实都是level order traversal的方式。
- python的iter没有hasNext()而是throw exception,所以就不用iterator实现了。
# Given two 1d vectors, implement an iterator to return their elements alternately.
# For example, given two 1d vectors:
# v1 = [1, 2]
# v2 = [3, 4, 5, 6]
# By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1, 3, 2, 4, 5, 6].
# Follow up: What if you are given k 1d vectors? How well can your code be extended to such cases?
# Clarification for the follow up question - Update (2015-09-18):
# The "Zigzag" order is not clearly defined and is ambiguous for k > 2 cases. If "Zigzag" does not look right to you, replace "Zigzag" with "Cyclic". For example, given the following input:
# [1,2,3]
# [4,5,6,7]
# [8,9]
# It should return [1,4,8,2,5,9,3,6,7].
# Hide Company Tags Google
# Hide Tags Design
# Hide Similar Problems (M) Binary Search Tree Iterator (M) Flatten 2D Vector (M) Peeking Iterator (M) Flatten Nested List Iterator
from collections import deque
class ZigzagIterator(object):
def __init__(self, v1, v2):
"""
Initialize your data structure here.
:type v1: List[int]
:type v2: List[int]
"""
self.data = deque([(0, v) for v in (v1, v2) if v])
def next(self):
"""
:rtype: int
"""
l, v = self.data.popleft()
ret = v[l]
if l<len(v)-1:
self.data.append((l+1, v))
return ret
def hasNext(self):
"""
:rtype: bool
"""
return bool(self.data)
# Your ZigzagIterator object will be instantiated and called as such:
# i, v = ZigzagIterator(v1, v2), []
# while i.hasNext(): v.append(i.next())