Given two 1d vectors, implement an iterator to return their elements alternately.
Example:
Input: v1 = [1,2] v2 = [3,4,5,6] Output:[1,3,2,4,5,6] Explanation:
By calling next repeatedly until hasNext returnsfalse
, 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:
Input:
[1,2,3]
[4,5,6,7]
[8,9]
Output: [1,4,8,2,5,9,3,6,7]
.
锯齿迭代器。
题意是给两个一维的向量,请交替输出他们的值。
常规思路就是为这两个向量分别创建一个iterator迭代器,然后从两个迭代器里交替输出元素。这里需要一个temp迭代器以用来帮助交换两个迭代器。
1 public class ZigzagIterator { 2 private Iterator<Integer> i, j, temp; 3 4 public ZigzagIterator(List<Integer> v1, List<Integer> v2) { 5 i = v2.iterator(); 6 j = v1.iterator(); 7 } 8 9 public int next() { 10 if (j.hasNext()) { 11 temp = i; 12 i = j; 13 j = temp; 14 } 15 return i.next(); 16 } 17 18 public boolean hasNext() { 19 return i.hasNext() || j.hasNext(); 20 } 21 } 22 23 /** 24 * Your ZigzagIterator object will be instantiated and called as such: 25 * ZigzagIterator i = new ZigzagIterator(v1, v2); 26 * while (i.hasNext()) v[f()] = i.next(); 27 */
这道题的followup是如果给K个一维的向量怎么处理。很显然如果有K个向量,那么自然还是需要K个迭代器来帮助输出来自于每个向量的元素,但是这里用temp来替换每个迭代器就不管用了。这里正确的思路是用一个queue存储所有的迭代器。每次调用next()函数的时候,就从queue中弹出一个迭代器。如果这个被弹出的迭代器里还有下一个元素,则弹出这个元素,并把这个迭代器再放回queue的末端;如果这个迭代器空了则无需再放回queue。
1 public class ZigzagIterator { 2 private Queue<Iterator> queue; 3 4 public ZigzagIterator(List<Integer> v1, List<Integer> v2) { 5 queue = new LinkedList<>(); 6 if (!v1.isEmpty()) { 7 queue.offer(v1.iterator()); 8 } 9 if (!v2.isEmpty()) { 10 queue.offer(v2.iterator()); 11 } 12 } 13 14 public int next() { 15 Iterator cur = queue.poll(); 16 Integer res = (Integer) cur.next(); 17 if (cur.hasNext()) { 18 queue.offer(cur); 19 } 20 return res; 21 } 22 23 public boolean hasNext() { 24 return !queue.isEmpty(); 25 } 26 } 27 28 /** 29 * Your ZigzagIterator object will be instantiated and called as such: 30 * ZigzagIterator i = new ZigzagIterator(v1, v2); 31 * while (i.hasNext()) v[f()] = i.next(); 32 */