251 Flatten 2D Vector
[
[1,2],
[3],
[4,5,6]
]class Vector2D {
public:
Vector2D(vector<vector<int>>& vec2d) {
v = &vec2d;
r = c = 0;
_skip_empty_vectors();
}
int next() {
// current r and c should always be valid
int cur_row = r, cur_col = c;
// update for next call
if (cur_col + 1 >= v->at(cur_row).size()) {
c = 0;
r++;
_skip_empty_vectors();
}
else c++;
return v->at(cur_row).at(cur_col);
}
bool hasNext() {
return r < v->size();
}
private:
int r, c;
vector<vector<int>> *v;
void _skip_empty_vectors() {
while (hasNext() && v->at(r).empty()) {
r++;
}
}
};Last updated