LeetCode刷题实战251:展开二维向量
Implement an iterator to flatten a 2d vector.
示例
Input: 2d vector =
[
[1,2],
[3],
[4,5,6]
]
Output: [1,2,3,4,5,6]
解题
class Vector2D {
public:
Vector2D(vector<vector<int>>& vec2d) {
if (vec2d.size() == 0) {
return;
}
row_it = vec2d.begin(), row_end = vec2d.end();
col_it = (*row_it).begin();
}
int next() {
return *col_it++;
}
bool hasNext() {
while (row_it != row_end && col_it == (*row_it).end()) {
++row_it;
col_it = (*row_it).begin();
}
return row_it != row_end;
}
private:
vector<vector<int>>::iterator row_it, row_end;
vector<int>::iterator col_it;
};
赞 (0)