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.
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(); } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/71863.html
摘要:另一個則是的迭代器,它負責記錄當前到哪一個的迭代器了。每次時,我們先調用一下,確保當前的迭代器有下一個值。代碼當前列表的迭代器為空,或者當前迭代器中沒有下一個值時,需要更新為下一個迭代器 Flatten 2D Vector Implement an iterator to flatten a 2d vector. For example, Given 2d vector = [ ...
閱讀 2960·2021-11-22 15:25
閱讀 2244·2021-11-18 10:07
閱讀 1052·2019-08-29 15:29
閱讀 479·2019-08-29 13:25
閱讀 1510·2019-08-29 12:58
閱讀 3206·2019-08-29 12:55
閱讀 2916·2019-08-29 12:28
閱讀 508·2019-08-29 12:16