Implement an iterator to flatten a 2d vector.

For example,
Given 2d vector =

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

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 函数即为取出当前位置元素,坐标后移一位,参见代码如下:

解法一:

  1. class Vector2D {
  2. public:
  3. Vector2D(vector<vector<int>>& vec2d) {
  4. for (auto a : vec2d) {
  5. v.insert(v.end(), a.begin(), a.end());
  6. }
  7. }
  8. int next() {
  9. return v[i++];
  10. }
  11. bool hasNext() {
  12. return i < v.size();
  13. }
  14. private:
  15. vector<int> v;
  16. int i = ;
  17. };

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

解法二:

  1. class Vector2D {
  2. public:
  3. Vector2D(vector<vector<int>>& vec2d): data(vec2d), x(), y() {}
  4.  
  5. int next() {
  6. hasNext();
  7. return data[x][y++];
  8. }
  9. bool hasNext() {
  10. while (x < data.size() && y == data[x].size()) {
  11. ++x;
  12. y = ;
  13. }
  14. return x < data.size();
  15. }
  16. private:
  17. vector<vector<int>> data;
  18. int x, y;
  19. };

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

解法三:

  1. class Vector2D {
  2. public:
  3. Vector2D(vector<vector<int>>& vec2d): x(vec2d.begin()), end(vec2d.end()) {}
  4.  
  5. int next() {
  6. hasNext();
  7. return (*x)[y++];
  8. }
  9. bool hasNext() {
  10. while (x != end && y == (*x).size()) {
  11. ++x;
  12. y = ;
  13. }
  14. return x != end;
  15. }
  16. private:
  17. vector<vector<int>>::iterator x, end;
  18. int y = ;
  19. };

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. ASP.NET Core 中文文档 第三章 原理(14)服务器

    原文:Servers 作者:Steve Smith 翻译:谢炀(Kiler) 校对:许登洋(Seay).姚阿勇(Dr.Yao) ASP.NET Core 已完全从承载应用程序的 Web 服务器环境中分 ...

  2. JS魔法堂:不完全国际化&本地化手册 之 实战篇

    前言  最近加入到新项目组负责前端技术预研和选型,其中涉及到一个熟悉又陌生的需求--国际化&本地化.熟悉的是之前的项目也玩过,陌生的是之前的实现仅仅停留在"有"的阶段而已. ...

  3. afxcomctl32.h与afxcomctl32.inl报错

    afxcomctl32.h与afxcomctl32.inl报错 编译公司一个几年前的老项目,是从VC6.0升级到VS2005的. 1.编译时报缺少头文件,于是附件包含目录,于是出现了以下报错: 1&g ...

  4. ABP学习日记1

  5. 学习Redis你必须了解的数据结构——JS实现集合和ECMA6集合

    集合类似于数组,但是集合中的元素是唯一的,没有重复值的.就像你学高中数学的概念一样,集合还可以做很多比如,并集,交集,差集的计算.在ECMA6之前,JavaScript没有提供原生的Set类,所以只能 ...

  6. shiro的使用1 简单的认证

    最近在重构,有空学了一个简单的安全框架shiro,资料比较少,在百度和google上能搜到的中文我看过了,剩下的时间有空会研究下官网的文章和查看下源码, 简单的分享一些学习过程: 1,简单的一些概念上 ...

  7. Linux(十)___iptables防火墙

    一.防火墙的作用 三.防火墙的分类 三.iptables基本语法: 表: 常用filter,nat用于地址映射转换. 配置文件: /etc/sysconfig/iptables 过滤表信息 . 查看i ...

  8. JavaScript 数据属性和访问器属性

    在JavaScript中对象被定义为"无序属性的集合,其属性可以包含基本值.对象或函数."通俗点讲,我们可以把对象理解为一组一组的名值对,其中值可以是数据或函数. 创建自定义对象通 ...

  9. BCS datetime 时间区间问题

    BCS 整合sql表时发现以下问题: datetime字段在列表中带了时区,比如插入12-6号的数据,在sql中显示的是12-5 date类型字段无法正确识别,插入成功但报错 LobSystem (外 ...

  10. iOS通知的整理笔记

    iOS通知用于高耦合界面的传值确实方便快捷. 需要实现模态弹出的视图控制器上,有一个视图控制器可以导航.这必定要将这个视图控制器的导航视图控制器naVC.view添加到模态弹出的视图控制器presen ...