LeetCode 251. Flatten 2D Vector

本文介绍了一种用于遍历不规则二维向量的有效方法。通过使用两个索引变量,文章详细阐述了如何处理包含空子向量的情况,并提供了两种不同实现方案的对比。此外,还讨论了如何维护不变量以简化代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值