Zigzag Iterator ii

来源:互联网 发布:下载输入法软件 编辑:程序博客网 时间:2024/05/23 02:00

Follow up Zigzag Iterator: 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".

Example

Given k = 3 1d vectors:

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

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

java 

public class ZigzagIterator2 {    /*    * @param vecs: a list of 1d vectors    */    List<Iterator<Integer>> list;    int count;    public ZigzagIterator2(List<List<Integer>> vecs) {        // do intialization if necessary        count = 0;        list = new ArrayList<Iterator<Integer>>();        for (List<Integer> li : vecs) {            if (!li.isEmpty()) {                list.add(li.iterator());            }        }    }    /*     * @return: An integer     */    public int next() {        // write your code here        int ele = list.get(count).next();        if (list.get(count).hasNext()) {            count = (count + 1) % list.size();        } else {            list.remove(count);            if (!list.isEmpty()) {                count %= list.size();            }        }        return ele;    }    /*     * @return: True if has next     */    public boolean hasNext() {        // write your code here        return list.size() > 0;    }}/** * Your ZigzagIterator2 object will be instantiated and called as such: * ZigzagIterator2 solution = new ZigzagIterator2(vecs); * while (solution.hasNext()) result.add(solution.next()); * Output result */

原创粉丝点击