251. Flatten 2D Vector 平铺二维矩阵

Implement an iterator to flatten a 2d vector.

Example:

Input: 2d vector =
[
  [1,2],
  [3],
  [4,5,6]
]
Output: [1,2,3,4,5,6]
Explanation: By calling next repeatedly until hasNext returns false, 
             the order of elements returned by next should be: [1,2,3,4,5,6].

思路:一大一小两个Iterator,小的是大的下一个循环

具体看注释

class Vector2D {
    //大的
    private Iterator<List<Integer>> i;
    //小的
    private Iterator<Integer> j;

    public Vector2D(List<List<Integer>> vec2d) {
        //大的
        i = vec2d.iterator();
    }

    public int next() {
        hasNext();
        //返回小的的下一个
        return j.next();
    }

    public boolean hasNext() {
        //i j 都有下一个元素,并且小的已空的时候
        while ((j == null || !j.hasNext()) && i.hasNext())
            //小的是大的下一个循环
            j = i.next().iterator();
        //返回小的是否有一下一个元素就行了
        return j != null && j.hasNext();
    }
}
View Code

 



posted @ 2020-08-04 07:49  苗妙苗  阅读(97)  评论(0编辑  收藏  举报