[LeetCode] 251. Flatten 2D Vector

发布时间:2019-06-22 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了[LeetCode] 251. Flatten 2D Vector脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

PRoblem

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].

Follow up:
As an added challenge, try to code it using only iterators in C++ or iterators in Java.

Solution

public class Vector2D implements Iterator<Integer> {
    private Iterator<List<Integer>> rows;
    private Iterator<Integer> row;
    
    public Vector2D(List<List<Integer>> vec2d) {
        rows = vec2d.iterator();
    }

    public Integer next() {
        if (hasNext()) return row.next();
        else return null;
        
    }

    //hasNext() is actually moving row iterator to next row 
    //when it's null or reached the end of current row
    public boolean hasNext() {
        while ((row == null || !row.hasNext()) && rows.hasNext()) {
            row = rows.next().iterator();
        }
        return row != null && row.hasNext();
    }
}

脚本宝典总结

以上是脚本宝典为你收集整理的[LeetCode] 251. Flatten 2D Vector全部内容,希望文章能够帮你解决[LeetCode] 251. Flatten 2D Vector所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。