Fork me on GitHub

Flatten 2D Vector

Description

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

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Vector2D {
private:
vector<vector<int>> vec;
vector<vector<int>>::iterator rowIter;
vector<int>::iterator columnIter;
public:
Vector2D(vector<vector<int>>& vec2d) {
vec = vec2d;
rowIter = vec.begin();
while (rowIter != vec.end() && rowIter->size() == 0) ++rowIter;
if (rowIter != vec.end()) columnIter = rowIter->begin();
}

int next() {
int ret = *columnIter;
++columnIter;
if (columnIter == rowIter->end()) {
++rowIter;
while (rowIter != vec.end() && rowIter->size() == 0) ++rowIter;
if (rowIter != vec.end()) columnIter = rowIter->begin();
}
return ret;
}

bool hasNext() {
if (rowIter == vec.end()) return false;
return true;
}
};

/**
* Your Vector2D object will be instantiated and called as such:
* Vector2D i(vec2d);
* while (i.hasNext()) cout << i.next();
*/