2015年9月14日星期一

Zigzag Iterator

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?

public class ZigzagIterator {

    Iterator<Integer> i1;
    Iterator<Integer> i2;
 
    boolean isNexti1;

    public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
        isNexti1 = true;
        i1 = v1.iterator();
        i2 = v2.iterator();
    }

    public int next() {
        int next = 0;
        if (isNexti1) {
            if (i1.hasNext()) {
                next = i1.next();
            } else {
                next = i2.next();
            }
        } else {
            if (i2.hasNext()) {
                next = i2.next();
            } else {
                next = i1.next();
            }
        }
        isNexti1 = !isNexti1;
        return next;
    }

    public boolean hasNext() {
        return i1.hasNext() || i2.hasNext();
    }
}

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

public class ZigzagIterator {
   
    Queue<Iterator<Integer>> queue = new LinkedList<>();

    public ZigzagIterator(List<Integer> v1, List<Integer> v2) {
        if (v1 != null && v1.iterator().hasNext()) {
            queue.offer(v1.iterator());
        }
        if (v2 != null && v2.iterator().hasNext()) {
            queue.offer(v2.iterator());
        }
    }

    public int next() {
        Iterator<Integer> iterator = queue.poll();
        int next = iterator.next();
        if (iterator.hasNext()) {
            queue.offer(iterator);
        }
        return next;
    }

    public boolean hasNext() {
        return !queue.isEmpty();
    }
}

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

没有评论:

发表评论