题目链接: https://leetcode.com/problems/flatten-2d-vector/
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 returns false, the order of elements returned by next should be: [1,2,3,4,5,6]
.
Hint:
- How many variables do you need to keep track?
- Two variables is all you need. Try with
x
andy
. - Beware of empty rows. It could be the first few rows.
- To write correct code, think about the invariant to maintain. What is it?
- The invariant is
x
andy
must always point to a valid point in the 2d vector. Should you maintain your invariant ahead of time or right when you need it? - Not sure? Think about how you would implement
hasNext()
. Which is more complex? - Common logic in two different places should be refactored into a common method.
Follow up:
As an added challenge, try to code it using only iterators in C++ or iterators in Java.
思路: 可以维护三个迭代器, 感觉要求说只要维护两个遍历有点不太可能. java或许可以.
代码各自如下:
class Vector2D {
public:
Vector2D(vector<vector<int>>& vec2d) {
if(vec2d.size() == 0) return;
it1 = vec2d.begin();
itEnd = vec2d.end();
it2 = (*it1).begin();
}
int next() {
return *it2++;
}
bool hasNext() {
while(it1 != itEnd && it2 == (*it1).end())
{
it1++;
it2 = (*it1).begin();
}
return it1 != itEnd;
}
private:
vector<vector<int>>::iterator it1, itEnd;
vector<int>::iterator it2;
};
/**
* Your Vector2D object will be instantiated and called as such:
* Vector2D i(vec2d);
* while (i.hasNext()) cout << i.next();
*/