Flatten 2D Vector -- LeetCode

时间:2023-03-09 00:03:22
Flatten 2D Vector -- LeetCode

Implement an iterator to flatten a 2d vector.

For example,
Given 2d vector =

[
[,],
[],
[,,]
]

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

 class Vector2D {
public:
int height, nextRow, nextCol;
vector<vector<int> > vec;
Vector2D(vector<vector<int>>& vec2d) {
vec = vec2d;
height = vec.size();
nextRow = nextCol = ;
} int next() {
int res = vec[nextRow][nextCol++];
if (nextCol == vec[nextRow].size()) {
nextCol = ;
nextRow++;
}
return res;
} //skip empty sub arrays
bool hasNext() {
while (nextRow < vec.size() && nextCol == vec[nextRow].size()) {
nextCol = ;
nextRow++;
}
return nextRow < vec.size();
}
}; /**
* Your Vector2D object will be instantiated and called as such:
* Vector2D i(vec2d);
* while (i.hasNext()) cout << i.next();
*/