成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

[LeetCode] 251. Flatten 2D Vector

curried / 2355人閱讀

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();
    }
}

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/71863.html

相關(guān)文章

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

    摘要:另一個(gè)則是的迭代器,它負(fù)責(zé)記錄當(dāng)前到哪一個(gè)的迭代器了。每次時(shí),我們先調(diào)用一下,確保當(dāng)前的迭代器有下一個(gè)值。代碼當(dāng)前列表的迭代器為空,或者當(dāng)前迭代器中沒(méi)有下一個(gè)值時(shí),需要更新為下一個(gè)迭代器 Flatten 2D Vector Implement an iterator to flatten a 2d vector. For example, Given 2d vector = [ ...

    MageekChiu 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<