540.Zigzag Iterator
1.Description(Medium)
Given two 1d vectors, implement an iterator to return their elements alternately.
Example
Given two 1d vectors:
v1 = [1, 2]
v2 = [3, 4, 5, 6]By calling next repeatedly until hasNext returnsfalse, the order of elements returned by next should be:[1, 3, 2, 4, 5, 6].
2.Code
public class ZigzagIterator {
/**
* @param v1 v2 two 1d vectors
*/
public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
// initialize your data structure here.
}
public int next() {
// Write your code here
}
public boolean hasNext() {
// Write your code here
}
}
/**
* Your ZigzagIterator object will be instantiated and called as such:
* ZigzagIterator solution = new ZigzagIterator(v1, v2);
* while (solution.hasNext()) result.add(solution.next());
* Output result
*/Version 1:数组法:跟Solution 601 Flatten 2D Vector解法几乎一模一样
注意交叉把元素放进类变量数组counter里面,哪个数组还剩下元素在一起放进去
Version 2: Iterator法:
Last updated
Was this helpful?