发布于 2016-01-02 21:37:14 | 299 次阅读 | 评论: 0 | 来源: PHPERZ
Leetcode 在线编程网站
leetcode 是一个美国的在线编程网站,上面主要收集了各大IT公司的笔试面试题,对于应届毕业生找工作是一个不可多得的好帮手。
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?
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]
.
这种题的通用解法就是用一个Queue来装所有iterator, next()的时候,pop一个iterator, 取对应iterator.next()
, 如果之后iterator.hasNext()
再把该iterator push回到Queue中。
关键就是Queue中所存在的iterator必须hasNext(),所有写Constructor时也要注意。
time: O(n), space: O(n)
public class ZigzagIterator {
Queue<Iterator<Integer>> q;
public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
q = new LinkedList<Iterator<Integer>>();
Iterator<Integer> it1 = v1.iterator();
Iterator<Integer> it2 = v2.iterator();
// 保证Queue中的Iterator hasNext().
if (it1.hasNext())
q.add(it1);
if (it2.hasNext())
q.add(it2);
}
public int next() {
Iterator<Integer> it = q.remove();
int res = it.next();
if (it.hasNext()) {
q.add(it);
}
return res;
}
public boolean hasNext() {
return !q.isEmpty();
}
}