题目来源
题目描述
class Vector2D {
public:
Vector2D(std::vector<std::vector<int>> v){
}
bool has_next(){
}
int next(){
}
};
题目解析
思路
class Vector2D {
std::vector<std::vector<int>> m;
int row;
int col; //迭代器光标位置
bool canUse; //光标所指位置是否已经被使用过
public:
Vector2D(std::vector<std::vector<int>> v){
m = std::move(v);
row = 0, col = -1;
canUse = true; //认为[0, -1]使用过
has_next();
}
bool has_next(){
if(row == m.size()){
return false; //超过终止行了
}
if(!canUse){ //当前数还没有被使用过
return true;
}
// (row, col) 被使用过了, 要去下一个了
if(col == m[row].size() - 1){
col = 0;
do{ //跳过空行
row++;
}while (row < m.size() && m[row].empty());
}else{
col++;
}
// 新的(row, col)
if(row != m.size()){
canUse = false;
return true;
}else{
return false; //到了终止行
}
}
int next(){
int ans = m[row][col];
canUse = true;
has_next();
return ans;
}
};
思路
- 将二维数组按照顺序先存入一个一维数组里面
- 然后维护一个变量i来记录当前遍历到的位置
- hasNext看当前坐标是否小于元素总数
- next:取出当前位置元素,坐标后移一位
class Vector2D {
std::vector<int> v;
int i = 0;
public:
Vector2D(std::vector<std::vector<int>> v2d){
for(auto a : v2d){
v.insert(v.end(), a.begin(), a.end());
i = 0;
}
}
bool has_next(){
return i < v.size();
}
int next(){
return v[i++];
}
};
思路
- 拷贝原始元素,然后维护两个变量x和y。
- 初始时x和y均为0
- hasNext:
- 先判断 x < 总行数?
- 如果成立,说明还没有遍历完,
- 那么判断 y == 当前行的列数?如果成立,说明要转到下一行,则x自增1,y初始化为0
- 接着判断x < 总行数?如果成立,说明下一个值可以被取出来
- 如果成立,说明还没有遍历完,
- 先判断 x < 总行数?
- next:返回data[x][y++]
class Vector2D {
vector<vector<int>> data;
int x, y;
public:
Vector2D(vector<vector<int>>& vec2d): data(vec2d), x(0), y(0) {}
bool has_next(){
while (x < data.size() && y == data[x].size()){
++x;
y = 0;
}
return x < data.size();
}
int next(){
has_next();
return data[x][y];
}
};
Follow up
class Vector2D {
vector<vector<int>>::iterator x, end;
int y = 0;
public:
Vector2D(vector<vector<int>>& vec2d): x(vec2d.begin()), end(vec2d.end()){}
bool hasNext(){
while (x != end && y == (*x).size()){
++x;
y = 0;
}
return x != end;
}
int next(){
hasNext();
return (*x)[y++];
}
};