Flatten 2D Vector

Description

Implement an iterator to flatten a 2d vector.

Example

Example 1:

Input:[[1,2],[3],[4,5,6]]
Output:[1,2,3,4,5,6]

Example 2:

Input:[[7,9],[5]]
Output:[7,9,5]

public class Vector2D implements Iterator<Integer> {

    private Iterator<List<Integer>> i;
    private Iterator<Integer> j;

    public Vector2D(List<List<Integer>> vec2d) {
        // Initialize your data structure here
        i = vec2d.iterator();
        j = null;
    }

    @Override
    public Integer next() {
        // Write your code here
        if (!hasNext()) {
            return null;
        }
        return j.next();
    }

    @Override
    public boolean hasNext() {
        // Write your code here
        while ((j == null || !j.hasNext()) && i.hasNext())
            j = i.next().iterator();
        return j != null && j.hasNext();
    }

    @Override
    public void remove() {}
}


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

  

猜你喜欢

转载自www.cnblogs.com/FLAGyuri/p/12078572.html
2D
今日推荐