首页 > 其他 > 详细

[LeetCode]Flatten 2D Vector

时间:2015-11-30 07:15:47      阅读:335      评论:0      收藏:0      [点我收藏+]
public class Vector2D {
    
    int row;
    int r;
    int c;
    List<List<Integer>> num;

    public Vector2D(List<List<Integer>> vec2d) {
        this.num = vec2d;
        r = 0; c = 0;
        row = num.size();
    }

    public int next() {
        while (r < row && c >= num.get(r).size()) {
            r ++;
            c = 0;
        }
        return num.get(r).get(c++);
    }

    public boolean hasNext() {
        while (r < row && c >= num.get(r).size()) {
            r ++;
            c = 0;
        }
        if (r >= row) {
            return false;
        }
        return c < num.get(r).size();
    }
}

Iterator解法

public class Vector2D {
    Iterator<List<Integer>> row_it;
    Iterator<Integer> col_it;
    List<List<Integer>> nums;
    public Vector2D(List<List<Integer>> vec2d) {
        this.nums = vec2d;
        row_it = nums.iterator();
        if (row_it.hasNext()) {
            col_it = row_it.next().iterator();
        }
    }

    public int next() {
        while(row_it.hasNext() && col_it != null && !col_it.hasNext()) {
            col_it = row_it.next().iterator();
        }
        return col_it.next();
    }

    public boolean hasNext() {
        while(row_it.hasNext() && col_it != null && !col_it.hasNext()) {
            col_it = row_it.next().iterator();
        }
        if (col_it == null || !col_it.hasNext()) {
            return false;
        }
        return true;
    }
}

 

[LeetCode]Flatten 2D Vector

原文:http://www.cnblogs.com/vision-love-programming/p/5006193.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!