博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] 251. Flatten 2D Vector
阅读量:7173 次
发布时间:2019-06-29

本文共 949 字,大约阅读时间需要 3 分钟。

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

转载地址:http://lgbzm.baihongyu.com/

你可能感兴趣的文章
HTML DOM 属性 对象
查看>>
Python基础25_模块, import,
查看>>
Algs4-1.3.27编写一个max()
查看>>
ubuntu12.04装有线网卡驱动(AR8162)
查看>>
迭代器
查看>>
多线程有几种实现方法?同步有几种实现方法
查看>>
element-ui 分页中的slot的用法(自定义分页显示内容)
查看>>
程序员的Lua快速入门
查看>>
Django 代码初体验
查看>>
大数据及智能信息系统
查看>>
[杂记]拜占庭将军问题
查看>>
关于数据请求中的多级联动的问题
查看>>
用jQuery和ajax实现搜索框文字自动补全功能
查看>>
hausaufgabe--python 27 - set
查看>>
分享职场心得《5》
查看>>
利用Response.Buffer做类似异步效果
查看>>
Nyoj 修路方案(次小生成树)
查看>>
git 使用
查看>>
毕业论文管理系统9
查看>>
动态规划初步习题(紫书)
查看>>