281. Zigzag Iterator
Problem description:
Given two 1d vectors, implement an iterator to return their elements alternately.
Example:1
2
3
4
5Input:
v1 = [1,2]
v2 = [3,4,5,6]
Output: [1,3,2,4,5,6]
Explanation: 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:
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:1
2
3
4
5
6Input:
[1,2,3]
[4,5,6,7]
[8,9]
Output: [1,4,8,2,5,9,3,6,7].
Solution:
The idea of this problem is to use a queue to store the current iterator of each vector. At start, we need to store the begin
and end
iterator of each vector. Every time we need to output a value, we take the pair<begin, end>
from the queue. After we get the pair
, we can use the begin
iterator to find next element in that vector.
- Use a queue to store iterators of each vector, push pairs of iterators with the zigzag order.
- Take the front element of the queue, pop it out. If we add 1 to the begin iterator, then we can get to the next element in the vector. However, if the begin iterator is equal to the end iterator, that means we reach to the end. And we don’t need to push the pair in to queue again.
1 | class ZigzagIterator { |
time complexity: $O(n)$
space complexity: $O(n)$
reference: