[leetcode] 251. Flatten 2D Vector 解题报告

这篇博客详细解析了LeetCode中的251题,要求实现一个迭代器来扁平化二维向量。文章讨论了如何处理空行,并强调了保持两个变量的有效性作为不变量的重要性,同时提出了重构重复逻辑到公共方法的建议。作者认为虽然题目要求仅用两个变量,但在Java中可能需要三个迭代器来完成任务。

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

题目链接: 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:

  1. How many variables do you need to keep track?
  2. Two variables is all you need. Try with x and y.
  3. Beware of empty rows. It could be the first few rows.
  4. To write correct code, think about the invariant to maintain. What is it?
  5. 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?
  6. Not sure? Think about how you would implement hasNext(). Which is more complex?
  7. 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();
 */


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值