251. Flatten 2D Vector 平铺矩阵

Design and implement an iterator to flatten a 2d vector. It should support the following operations: next and hasNext.

 

Example:

Vector2D iterator = new Vector2D([[1,2],[3],[4]]);

iterator.next(); // return 1
iterator.next(); // return 2
iterator.next(); // return 3
iterator.hasNext(); // return true
iterator.hasNext(); // return true
iterator.next(); // return 4
iterator.hasNext(); // return false

思路:

两者之中有一个存在next()就行了
这个思路不对,只能从colIter中取next。所以应该是next()中只有一个功能:返回col_itr.next()

 

 

如果一开始就用while循环,1,2,3,4 调用next直接返回最后一个了
所以一开始要用if 先存一行 保证next()直接调用是有东西的

 

 

这个代码signature不一样,无法通过,但是思路是对的:

public class Vector2D implements Iterator<Integer> {
    private Iterator<List<Integer>> row_itr; //row iterator
    private Iterator<Integer> col_itr;       //col iterator

    public Vector2D(List<List<Integer>> vec2d) {
        row_itr = vec2d.iterator();
        //if row_itr doesn't have next, it means vec2d is empty
        //in this case, col_itr won't get initialized
        if(row_itr.hasNext())
            col_itr = row_itr.next().iterator();
    }

    @Override
    public Integer next() {
        //we won't call next() unless we are sure that hasNext() is true, meaning col_itr.hasNext() is true
        return col_itr.next();
    }

    @Override
    public boolean hasNext() {
        //check whether vec2d is empty
        if(col_itr==null) return false;
        
        //important!!! we do update here in hasNext()
        //update col_itr and row_itr until col_itr.hasNext() or row_itr.hasNext() is false
        while(!col_itr.hasNext()&&row_itr.hasNext())
            col_itr = row_itr.next().iterator();
        
        return col_itr.hasNext();      
    }
}
View Code

 

 

 
posted @ 2020-09-26 00:46  苗妙苗  阅读(136)  评论(0编辑  收藏  举报