博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Flatten 2D Vector 压平二维向量
阅读量:7078 次
发布时间:2019-06-28

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

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  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  or .

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

解法一:

class Vector2D {public:    Vector2D(vector
>& 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
v; int i = 0;};

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

解法二:

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

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

解法三:

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

本文转自博客园Grandyang的博客,原文链接:,如需转载请自行联系原博主。

你可能感兴趣的文章
使用vue实现tab操作
查看>>
vim 编辑器简介
查看>>
LDAP开发学习
查看>>
JavaScript——作用域、变量声明提升、局部变量混谈
查看>>
Vue 2.0 入门系列(7)组件实例之模态框
查看>>
关于JavaScropt函数式编程,我多么希望能早点看到这本书
查看>>
Yii2实现ActiveForm ajax提交
查看>>
【译】State and Lifecycle (State和生命周期)
查看>>
C接口与实现---之三
查看>>
Swift 个人学习笔记 - 06: 控制流
查看>>
Oracle弃用Nashorn JavaScript引擎
查看>>
浅析React之事件系统(一)
查看>>
解密新一代Java JIT编译器Graal
查看>>
HTTP协议:看个新闻原来这么麻烦
查看>>
故障转移架构的本质:数据中心的基础设施过剩
查看>>
服务平台化,知乎 HBase 实践
查看>>
取代ZooKeeper!高并发下的分布式一致性开源组件StateSynchronizer
查看>>
关于CarbonData+Spark SQL的一些应用实践和调优经验分享
查看>>
GitLab Web IDE正式发布10.7版本并开源
查看>>
微服务通信策略
查看>>