Implement an iterator to flatten a 2d vector.

For example,
Given 2d vector =

[
[1,2],
[3],
[4,5,6]
]

By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,2,3,4,5,6].

Hint:

  1. How many variables do you need to keep track?
  2. Two variables is all you need. Try with x and y.
  3. Beware of empty rows. It could be the first few rows.
  4. To write correct code, think about the invariant to maintain. What is it?
  5. The invariant is x and y must always point to a valid point in the 2d vector. Should you maintain your invariant ahead of time or right when you need it?
  6. Not sure? Think about how you would implement hasNext(). Which is more complex?
  7. Common logic in two different places should be refactored into a common method.

Follow up:
As an added challenge, try to code it using only iterators in C++ or iterators in Java.

这道题让我们压平一个二维向量数组,并且实现一个 iterator 的功能,包括 next 和 hasNext 函数,那么最简单的方法就是将二维数组按顺序先存入到一个一维数组里,然后此时只要维护一个变量i来记录当前遍历到的位置,hasNext 函数看当前坐标是否小于元素总数,next 函数即为取出当前位置元素,坐标后移一位,参见代码如下:

解法一:

class Vector2D {
public:
Vector2D(vector<vector<int>>& vec2d) {
for (auto a : vec2d) {
v.insert(v.end(), a.begin(), a.end());
}
}
int next() {
return v[i++];
}
bool hasNext() {
return i < v.size();
}
private:
vector<int> v;
int i = ;
};

下面我们来看另一种解法,不直接转换为一维数组,而是维护两个变量x和y,将x和y初始化为0,对于 hasNext 函数,检查当前x是否小于总行数,y是否和当前行的列数相同,如果相同,说明要转到下一行,则x自增1,y初始化为0,若此时x还是小于总行数,说明下一个值可以被取出来,那么在 next 函数就可以直接取出行为x,列为y的数字,并将y自增1,参见代码如下:

解法二:

class Vector2D {
public:
Vector2D(vector<vector<int>>& vec2d): data(vec2d), x(), y() {} int next() {
hasNext();
return data[x][y++];
}
bool hasNext() {
while (x < data.size() && y == data[x].size()) {
++x;
y = ;
}
return x < data.size();
}
private:
vector<vector<int>> data;
int x, y;
};

题目中的 Follow up 让我们用 interator 来做,C++中 iterator 不像 Java 中的那么强大,自己本身并没有包含 next 和 hasNext 函数,所以得自己来实现,将x定义为行的 iterator,再用个 end 指向二维数组的末尾,定义一个整型变量y来指向列位置,实现思路和上一种解法完全相同,只是写法略有不同,参见代码如下:

解法三:

class Vector2D {
public:
Vector2D(vector<vector<int>>& vec2d): x(vec2d.begin()), end(vec2d.end()) {} int next() {
hasNext();
return (*x)[y++];
}
bool hasNext() {
while (x != end && y == (*x).size()) {
++x;
y = ;
}
return x != end;
}
private:
vector<vector<int>>::iterator x, end;
int y = ;
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/251

类似题目:

Binary Search Tree Iterator

Zigzag Iterator

Peeking Iterator

Flatten Nested List Iterator

参考资料:

https://leetcode.com/problems/flatten-2d-vector/

https://leetcode.com/problems/flatten-2d-vector/discuss/67652/7-9-lines-added-Java-and-C%2B%2B-O(1)-space.

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Flatten 2D Vector 压平二维向量的更多相关文章

  1. [LeetCode] 251. Flatten 2D Vector 压平二维向量

    Implement an iterator to flatten a 2d vector. For example,Given 2d vector = [ [1,2], [3], [4,5,6] ] ...

  2. 用vector实现二维向量

    如果一个向量的每一个元素是一个向量,则称为二维向量,例如 vector<vector<int> >vv(3, vector<int>(4));//这里,两个“> ...

  3. LeetCode Flatten 2D Vector

    原题链接在这里:https://leetcode.com/problems/flatten-2d-vector/ 题目: Implement an iterator to flatten a 2d v ...

  4. [Swift]LeetCode251.展平二维向量 $ Flatten 2D Vector

    Implement an iterator to flatten a 2d vector. For example,Given 2d vector = [ [1,2], [3], [4,5,6] ] ...

  5. [VB.NET][C#]二维向量的基本运算

    前言 在数学中,几何向量指具有大小(Magnitude)和方向的几何对象,它在线性代数中经由抽象化有着更一般的概念.向量在编程中也有着及其广泛的应用,其作用在图形编程和游戏物理引擎方面尤为突出. 基于 ...

  6. uda 3.C++二维向量

    二维向量 接下来,你将使用向量来存储矩阵.就像 Python 使用列表列表来存储矩阵一样,C++ 使用的是向量的向量.用于声明二维向量的语法有点复杂. 假设你正在使用 Python,并且想存储一个 3 ...

  7. 【Unity3D】计算二维向量夹角(-180到180)

    在Unity3D中,有时候我们需要计算二维向量的夹角.二维向量夹角一般在0~180度之前,可以直接调用Vector2.Angle(Vector2 from, Vector2 to)来计算. 但是在有些 ...

  8. 251. Flatten 2D Vector 平铺二维矩阵

    [抄题]: Implement an iterator to flatten a 2d vector. Example: Input: 2d vector = [ [1,2], [3], [4,5,6 ...

  9. LeetCode 251. Flatten 2D Vector

    原题链接在这里:https://leetcode.com/problems/flatten-2d-vector/ 题目: Implement an iterator to flatten a 2d v ...

随机推荐

  1. "bower.json 中出现语法错误" 的解决方案之一

    当你用 Visual Studio 2015 Update 3 打开从别处下载的开源项目的时候,如果发现 Bower 提示 "bower.json 中出现语法错误". 请检查一下. ...

  2. PHP多图片上传实例demo

    upload.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http:/ ...

  3. Servlet3.0的可插拔功能

    如果说 3.0 版本新增的注解支持是为了简化 Servlet/ 过滤器 / 监听器的声明,从而使得 web.xml 变为可选配置, 那么新增的可插性 (pluggability) 支持则将 Servl ...

  4. Delphi_09_Delphi_Object_Pascal_面向对象编程

    今天这里讨论一下Delphi中的面向对象编程,这里不做过多过细的讨论,主要做提纲挈领的描述,帮助自己抓做重点. 本随笔分为两部分: 一.面向对象编程 二.面向对象编程详细描述 ------------ ...

  5. 高效 Java Web 开发框架 JessMA v3.5.1

    JessMA 是功能完备的高性能 Full-Stack Web 应用开发框架,内置可扩展的 MVC Web 基础架构和 DAO 数据库访问组件(内部已提供了 Hibernate.MyBatis 与 J ...

  6. springmvc4 mybatis 整合 框架源码 bootstrap

    A集成代码生成器 [正反双向(单表.主表.明细表.树形表,开发利器)+快速构建表单 下载地址    ; freemaker模版技术 ,0个代码不用写,生成完整的一个模块,带页面.建表sql脚本,处理类 ...

  7. CentOS7中安装Python3.5

    1.下载 https://www.python.org/ftp/python/3.5.2/Python-3.5.2.tgz 2.上传到服务器 3. 安装相关依赖 yum install gcc ope ...

  8. Atitit 自然语言处理原理与实现 attilax总结

    Atitit 自然语言处理原理与实现 attilax总结 1.1. 中文分词原理与实现 111 1.2. 英文分析 1941 1.3. 第6章 信息提取 2711 1.4. 第7章 自动摘要 3041 ...

  9. ArcGIS Engine开发之地图基本操作(4)

    ArcGIS Engine开发中数据库的加载 1.加载个人地理数据库数据 个人地理数据库(Personal Geodatabase)使用Miscrosoft Access文件(*.mdb)进行空间数据 ...

  10. webView 自适应高度 document.body 属性

    前段时间开发遇到webView 高度自适应问题,用最初的方法无效,找了些资料,记录下. 1.若网页中含有< !DOCTYPE html PUBLIC "-//W3C//DTD XHTM ...