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(); } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/71863.html
摘要:另一个则是的迭代器,它负责记录当前到哪一个的迭代器了。每次时,我们先调用一下,确保当前的迭代器有下一个值。代码当前列表的迭代器为空,或者当前迭代器中没有下一个值时,需要更新为下一个迭代器 Flatten 2D Vector Implement an iterator to flatten a 2d vector. For example, Given 2d vector = [ ...
阅读 2920·2021-11-22 15:25
阅读 2221·2021-11-18 10:07
阅读 999·2019-08-29 15:29
阅读 459·2019-08-29 13:25
阅读 1483·2019-08-29 12:58
阅读 3153·2019-08-29 12:55
阅读 2893·2019-08-29 12:28
阅读 475·2019-08-29 12:16