[LeetCode] Flatten 2D Vector

简介: Problem Description:   Implement an iterator to flatten a 2d vector. For example,Given 2d vector = [ [1,2], [3], [4,5,6] ] By callin...

Problem Description:

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


The idea is very simple. We keep two variables row and col for the range of rows and cols. Specifically, row is the number of rows of vec2d and col is the number of columns of the current 1d vector in vec2d. We also keep two variables r and c to point to the current element.

In the constructor, we initialize row and col as above and initialize both r and c to be 0(pointing to the first element).

In hasNext(), we just need to check whether r and c are still in the range limited by row andcol.

In next(), we first record the current element, which is returned later. Then we update the running indexes and possibly the range if the current element is the last element of the current 1d vector.

A final and important note, since in next(), we record the current element, we need to guarantee that there is an element. So we implement a helper function skipEmptyVector() to skip the empty vectors. It is also important to handle the case that vec2d is empty (in this case, we set col = -1).

The time complexity of hasNext() is obviously O(1) and the time complexity of next is alsoO(1) in an amortized sense.

The code is as follows.

 1 class Vector2D {
 2 public:
 3     Vector2D(vector<vector<int>>& vec2d) {
 4         data = vec2d;
 5         r = c = 0;
 6         row = vec2d.size();
 7         col = (row == 0 ? -1 : data[r].size());
 8         skipEmptyVector();
 9     }
10 
11     int next() {
12         int elem = data[r][c];
13         if (c == col - 1) {
14             r++;
15             c = 0;
16             col = data[r].size();
17         }
18         else c++;
19         skipEmptyVector();
20         return elem;
21     }
22 
23     bool hasNext() {
24         return col != -1 && (r < row && c < col);
25     }
26 private:
27     vector<vector<int>> data;
28     int row, col, r, c;
29     void skipEmptyVector(void) {
30         while (!col) {
31             r++;
32             col = data[r].size();
33         }
34     }
35 };
36 
37 /**
38  * Your Vector2D object will be instantiated and called as such:
39  * Vector2D i(vec2d);
40  * while (i.hasNext()) cout << i.next();
41  */

Since we need to copy the vec2d anyway, we can just copy it into a simple vector<int>, which makes life much easier :-)

 1 class Vector2D {
 2 public:
 3     Vector2D(vector<vector<int>>& vec2d) {
 4         int row = vec2d.size();
 5         for (int r = 0; r < row; r++) {
 6             int col = vec2d[r].size();
 7             for (int c = 0; c < col; c++)
 8                 data.push_back(vec2d[r][c]);
 9         }
10         idx = 0;
11     }
12 
13     int next() {
14         return data[idx++];
15     }
16 
17     bool hasNext() {
18         return idx < data.size();
19     }
20 private:
21     vector<int> data;
22     int idx;
23 };
24 
25 /**
26  * Your Vector2D object will be instantiated and called as such:
27  * Vector2D i(vec2d);
28  * while (i.hasNext()) cout << i.next();
29  */

Of course, since elements in vector are stored in a contiguous range of memory, the problem can be solved in O(1) memory (see here for a better solution). 

目录
相关文章
|
11月前
|
Java
Leetcode 114. Flatten Binary Tree to Linked List
思路也很简单,先把root的左子树(如有)变成单链表 leftlinkedlist,把root的右子树(如有)变成单链表 rightlinkedlist,再把root的右节点变成leftlikedlist,再把rightlinkedlist接到leftlinkedlist后面,代码如下。
39 1
|
11月前
Leetcode 74. Search a 2D Matrix
这道题很简单,为此专门写篇博客其实算博客凑数了。给你一个每一行每一列都是增序,且每一行第一个数都大于上一行末尾数的矩阵,让你判断某个数在这个矩阵中是否存在。 假设矩阵是m*n,扫一遍的时间复杂度就是O(m*n),题目中给出的这么特殊的矩阵,时间复杂度可以降到O(m+n),具体代码如下,写的比较挫。
82 1
LeetCode 430. Flatten a Multilevel Doubly Linked
使用循环,从头开始遍历,将子链看成一个整体,将整体向上移动一层。 继续向后遍历,如果遇到子链,将其看作一层,将其整体向上移动,如此循环下去,直至结束。
73 0
LeetCode 430. Flatten a Multilevel Doubly Linked
LeetCode 341. Flatten Nested List Iterator
给定一个嵌套的整型列表。设计一个迭代器,使其能够遍历这个整型列表中的所有整数。 列表中的项或者为一个整数,或者是另一个列表。
67 0
LeetCode 341. Flatten Nested List Iterator
LeetCode 304. Range Sum Query 2D - Immutable
给定一个二维矩阵,计算其子矩形范围内元素的总和,该子矩阵的左上角为 (row1, col1) ,右下角为 (row2, col2)。
97 0
LeetCode 304. Range Sum Query 2D - Immutable
|
算法
LeetCode 74. Search a 2D Matrix
编写一个有效的算法,搜索m×n矩阵中的值。 此矩阵具有以下属性: 每行中的整数从左到右排序. 每行的第一个整数大于前一行的最后一个整数.
75 0
LeetCode 74. Search a 2D Matrix
|
存储 C语言 C++
Leetcode17. 电话号码的字母组合:递归树深度遍历(C++vector和string的小练习)
Leetcode17. 电话号码的字母组合:递归树深度遍历(C++vector和string的小练习)
LeetCode1290 二进制链表转整数C++解法(vector实现)
给你一个单链表的引用结点 head。链表中每个结点的值不是 0 就是 1。已知此链表是一个整数数字的二进制表示形式。 请你返回该链表所表示数字的 十进制值 。 示例1:
102 0
LeetCode1290 二进制链表转整数C++解法(vector实现)
【LeetCode剑指offer57 II】和为s的连续正数序列(用vector模拟滑动窗口)
因为找的是连续子序列(并且题目的原序列是从小到大元素排列)的和为target,所以使用滑动窗口,如果加上当前元素后sum满足条件则push_back
126 0
【LeetCode剑指offer57 II】和为s的连续正数序列(用vector模拟滑动窗口)
|
存储 算法 前端开发
从一道hard的leetcode到2d包围盒算法
前言 大家好,哈哈哈最近国庆在家无聊比较boring,然后最近也在学习算法,之前我是从来没有做过hard的题目。想着胖虎来挑战下。然后这道题也比较有意思,我不是什么算法大佬,我只是觉得这篇很有意义。读完这篇文章你可以学到什么: 空间中2d包围盒的概念 (boundingBox) 包围盒如何判断是否相交 多个包围盒如何如何联合一个大包围盒的 这就是为什么我要去分享这道题的原因,因为无论在3d或者2d中,你去判断「两个图形是否相交其实快速判断」 就是通过包围盒去做判断, 在游戏中你🤔一下,「一个游戏人物如何判断他是否走到墙壁了」。他是怎么实现碰撞的对吧, 游戏对象 都有一个「精灵」 和 「碰撞
从一道hard的leetcode到2d包围盒算法