Design and implement an iterator to flatten a 2d vector. It should support the following operations: next
and hasNext
.
Copy Vector2D iterator = new Vector2D([[1,2],[3],[4]]);
iterator.next(); // return 1
iterator.next(); // return 2
iterator.next(); // return 3
iterator.hasNext(); // return true
iterator.hasNext(); // return true
iterator.next(); // return 4
iterator.hasNext(); // return false
Copy class Vector2D {
public:
// queue, time: O(n); space: O(n)
Vector2D(vector<vector<int>> v) {
for (vector<int>& a : v) {
for (int num : a) {
q.push(num);
}
}
}
int next() {
int t = q.front(); q.pop();
return t;
}
bool hasNext() {
return !q.empty();
}
queue<int> q;
};
Copy class Vector2D {
public:
Vector2D(vector<vector<int>> v) : x(0), y(0) {
m_vec = v;
}
int next() {
if (hasNext()) return m_vec[x][y++];
return -1;
}
bool hasNext() {
while (x < m_vec.size()) {
if (y < m_vec[x].size()) {
return true;
} else {
y = 0;
++x;
}
}
return false;
}
vector<vector<int> > m_vec;
int x, y;
};
Copy class Vector2D {
public:
Vector2D(vector<vector<int>>& vec2d): x(vec2d.begin()), x_end(vec2d.end()) {}
int next() {
hasNext();
return (*x)[y++];
}
bool hasNext() {
while (x != x_end && y == (*x).size()) {
++x;
y = 0;
}
return x != x_end;
}
private:
vector<vector<int>>::iterator x, x_end;
int y = 0;
};
Copy class Vector2D {
public:
Vector2D(vector<vector<int>>& vec2d) {
x = vec2d.begin(), x_end = vec2d.end();
while (x != x_end && x->size() == 0) x++;
if (x != x_end) y = x->begin();
}
int next() {
hasNext();
return *y++;
}
bool hasNext() {
while(x != x_end && y == x->end()){
x++;
if(x == x_end) break;
y = x->begin();
}
if(x == x_end) return false;
return true;
}
vector<vector<int>>::iterator x, x_end; // row
vector<int>::iterator y; // col
};