I didn't buy the locked questions (This question is copied from other blog.)
Implement an iterator to flatten a 2d vector.
For example,
Given 2d vector =
[ [1,2], [3], [4,5,6] ]
By calling next repeatedly until hasNext returnsfalse, the order of elements returned by next should be:[1, 2, 3, 4, 5, 6].
2 Method: Extra O(n) and two pointers.
#include <vector>
#include <iostream>
using namespace std;
class Vector2D {
private:
vector< vector<int> >::iterator i, iEnd;
int j = 0;
public:
Vector2D(vector< vector<int> >& vec2d) {
i = vec2d.begin();
iEnd = vec2d.end();
}
int next() {
hasNext();
return (*i)[j++];
}
bool hasNext() {
while(i != iEnd && j == (*i).size()) {
i++;
j = 0;
}
return i != iEnd;
}
};
// O(n) extra space.
class Vector2DII {
private:
vector<int> innerVec;
int j = 0;
public:
Vector2DII(vector< vector<int> >& vec2d) {
for(int i = 0; i < vec2d.size(); ++i) {
for(int j = 0; j < vec2d[i].size(); ++j) {
innerVec.push_back(vec2d[i][j]);
}
}
}
int next() {
hasNext();
return innerVec[j++];
}
bool hasNext() {
return j == innerVec.size();
}
};
int main(void) {
vector< vector<int> > test{{1, 2}, {1}};
Vector2DII myVector(test);
cout << myVector.next() << endl;
cout << myVector.next() << endl;
cout << myVector.next() << endl;
}