Please remember to RESET your class variables declared in Vector2D, as static/class variables are persisted across multiple test cases. Please see for more details.
You may assume that next() call will always be valid, that is, there will be at least a next element in the 2d vector when next() is called.
Follow up:
As an added challenge, try to code it using only or .
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;
};
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;
};
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;
};
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
};