Leetcode Flatten 2D Vector

来源:互联网 发布:mac下常用软件 编辑:程序博客网 时间:2024/06/16 14:33

Implement an iterator to flatten a 2d vector.

For example,
Given 2d vector =

[  [1,2],  [3],  [4,5,6]]

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


Difficulty: Medium


public class Vector2D implements Iterator<Integer> {    List<List<Integer>> nums;    int col, row;    public Vector2D(List<List<Integer>> vec2d) {        col = 0;        row = 0;        nums = vec2d;    }    @Override    public Integer next() {        while(row < nums.size()){            if(col < nums.get(row).size()){                col++;                return nums.get(row).get(col - 1);            }            else{                col = 0;                row++;            }        }        return -1;    }    @Override    public boolean hasNext() {        while(row < nums.size()){            if(col < nums.get(row).size()){                return true;            }            else{                col = 0;                row++;            }        }        return false;            }}/** * Your Vector2D object will be instantiated and called as such: * Vector2D i = new Vector2D(vec2d); * while (i.hasNext()) v[f()] = i.next(); */


0 0
原创粉丝点击