281. Zigzag Iterator z字型遍历

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 returns false, 
the order of elements returned by next should be: [1,3,2,4,5,6].


不知道怎么去zigzag,想起来就很简单:
j=v1 返回一个值
j=v2 返回一个值
...两个iterator来回换

 

281. Zigzag Iterator z字型遍历
public class ZigzagIterator {
    Iterator<Integer> i;
    Iterator<Integer> j;

    public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
        i = v1.iterator();
        j = v2.iterator();
    }

    public int next() {
        if (i.hasNext()) {
            Iterator<Integer> temp = i;
            i = j;
            j = temp;
        }
        
        return j.next();
    }

    public boolean hasNext() {
        return (i.hasNext() || j.hasNext());
    }
}

/**
 * Your ZigzagIterator object will be instantiated and called as such:
 * ZigzagIterator i = new ZigzagIterator(v1, v2);
 * while (i.hasNext()) v[f()] = i.next();
 */
View Code

 

 
上一篇:java 导出pdf 功能


下一篇:Google Noto Sans CJK 字体