资讯专栏INFORMATION COLUMN

[LeetCode] 251. Flatten 2D Vector

curried / 2345人阅读

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 {
    private Iterator> rows;
    private Iterator row;
    
    public Vector2D(List> 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();
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/71863.html

相关文章

  • [Leetcode] Flatten 2D Vector 整平二维向量

    摘要:另一个则是的迭代器,它负责记录当前到哪一个的迭代器了。每次时,我们先调用一下,确保当前的迭代器有下一个值。代码当前列表的迭代器为空,或者当前迭代器中没有下一个值时,需要更新为下一个迭代器 Flatten 2D Vector Implement an iterator to flatten a 2d vector. For example, Given 2d vector = [ ...

    MageekChiu 评论0 收藏0

发表评论

0条评论

curried

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<