Follow upZigzag Iterator: What if you are givenk1d vectors? How well can your code be extended to such cases? The "Zigzag" order is not clearly defined and is ambiguous fork > 2cases. If "Zigzag" does not look right to you, replace "Zigzag" with "Cyclic".

Have you met this question in a real interview?

Yes

Example

Givenk = 31d vectors:

[1,2,3]
[4,5,6,7]
[8,9]

Return[1,4,8,2,5,9,3,6,7].

可以用I中一样的思路,改变Input即可

public class ZigzagIterator2 {
    /*
    * @param vecs: a list of 1d vectors
    */
    private List<List<Integer>> iterVecs;
    private Stack<Integer> stack;
    private int index;
    public ZigzagIterator2(List<List<Integer>> vecs) {
        // do intialization if necessary
        iterVecs = vecs;
        index = 0;
        stack = new Stack<Integer>();
    }

    /*
     * @return: An integer
     */
    public int next() {
        // write your code here
        return stack.pop();
    }

    /*
     * @return: True if has next
     */
    public boolean hasNext() {
        // write your code here
        if (stack.isEmpty()) {
            for (int i = iterVecs.size() - 1; i >= 0; i--) {
                if (index < iterVecs.get(i).size()) {
                    stack.push(iterVecs.get(i).get(index));
                }
            }
            index++;
        }

        return !stack.isEmpty();
    }
}

/**
 * Your ZigzagIterator2 object will be instantiated and called as such:
 * ZigzagIterator2 solution = new ZigzagIterator2(vecs);
 * while (solution.hasNext()) result.add(solution.next());
 * Output result
 */

results matching ""

    No results matching ""