LeetCode251 Flatten 2D Vector

this is a data structure design related problem.
it need to support to operations: next() and hasNext()

first, what data structure is it for us to contains those 2D array? the answer is 2D array.
besides, we need two more pointers, one points as indexElement, and another is indexRow.

even though I know how the general idea, the code I wrote is so bad compared to the right solution.
it actually reflected many of my bad behavior on coding:
too focused on current function: I decide to use next() to do all the pointer moving works, and did not realized that hasNext() can also do some kind of pointer moving work(like moving those two pointer to the next non null),
anyway, I wrote a pretty shitty solution and can’t even get accepted.
let’s enjoy the nice and clear codes provided by leetcode.

class Vector2D {
    
    private int[][] vec2d;
    private int indexElement;
    private int indexRow;


    public Vector2D(int[][] vec2d) {
        this.vec2d = vec2d;
        this.indexElement = 0;
        this.indexRow = 0;
    }


    //@Override
    public Integer next() {
        int res = -1;
        if (indexRow < vec2d.length) {
            res = vec2d[indexRow][indexElement]; 
            if (indexElement + 1 < vec2d[indexRow].length) {
                indexElement++;
            } else {
                indexRow++;
                indexElement = 0;
            }
        }
        return res;
        
    }

    //@Override
    public boolean hasNext() { //pay attention to how similar next() and hasNext() methogs
        while (indexRow < vec2d.length) {
            //res = vec2d[indexRow][indexElement]; 
            if (indexElement < vec2d[indexRow].length) {
                //indexElement++;
                return true;
            } else {
                indexRow++;
                indexElement = 0;
            }
        }
        return false;
    }
}

follow up: can you do it in iterator?
so this problem converted to, design a 2d matrix iterator.

public class Vector2D {
    Iterator<List<Integer>> itrs;
    Iterator<Integer> row;
    public Vector2D(List<List<Integer>> vec2d) {
        if(vec2d == null || vec2d.size() == 0) return;
        itrs = vec2d.iterator();
        row = itrs.next().iterator();
        getNextRow();
    }
    
    private void getNextRow(){ //while current row have no next and cureent list have next row, row keeps moving
        while(!row.hasNext() && itrs.hasNext()) row = itrs.next().iterator();
    }

    public int next() {
        int next = row.next();
        getNextRow(); //move to next non null
        return next;
    }

    public boolean hasNext() {
        return row != null && row.hasNext(); //check
    }
}
posted @ 2020-08-13 09:27  EvanMeetTheWorld  阅读(35)  评论(0)    收藏  举报