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 and y.
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 and y 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.
思路:
1. 这个题考虑的特殊情况就是给定的2D vector中间可能某一个vector是空的没有元素,所以判断hasNext()就要想办法跳过这些vector。
2. 根据hint,需要x,y来表示当前被访问元素的横纵坐标。在那个函数来修改x,y坐标这个问题容易被忽略。刚开始想的时候,潜意识默认就是在hasNext()修改两个坐标,在next()直接返回,但这样做稍微复杂了,见方法2。方法1,则是把坐标的变化分别在两个函数中完成,反而简单!这里,方法1简单的原因是结合了两个函数调用顺序固定的特点,而方法2是割裂开两个函数的关系!
//方法1:在hasNext()修改x的坐标,在next()修改y的坐标。
class Vector2D {
public:
Vector2D(vector<vector<int>>& vec2d) {
x=0;y=0;
v=vec2d;
}
int next() {
return v[x][y++];
}
bool hasNext() {
while(x<v.size()&&y==v[x].size()){
x++;
y=0;
}
return x<v.size();
}
private:
int x,y;
vector<vector<int>> v;
};
//方法2:只在hasNext()修改x,y的坐标;
class Vector2D {
public:
Vector2D(vector<vector<int>>& vec2d) {
x=0;y=-1;//y=-1,调用hasNext()会y++;
v=vec2d;
}
int next() {
return v[x][y];
}
bool hasNext() {
while(x<v.size()&&y==v[x].size()-1){//应对空vector
x++;
y=-1;
}
if(x<v.size()&&y<v[x].size()-1)
y++;
return x<v.size();
}
private:
int x,y;
vector<vector<int>> v;
};