251. Flatten 2D Vector

问题描述:

Implement an iterator to flatten a 2d vector.

Example:

Input: 2d vector =
[
  [1,2],
  [3],
  [4,5,6]
]
Output: [1,2,3,4,5,6]
Explanation: By calling next repeatedly until hasNext returns false, 
             the order of elements returned by next should be: [1,2,3,4,5,6].

Follow up:
As an added challenge, try to code it using only iterators in C++ or iterators in Java.

 

解题思路:

没看到啊follow up之前:

因为是两个数组嵌套,可以便利数组内的所有的元素,然后加入队列中。

每次取出队首并弹出。

 

只使用iterator来解答:

因为参数为引用传参,所以我们就可以直接存储传入数组的iterator。

注意在对内部数组的iterator进行赋值的时候,我们需要检查外部iterator是否有效。

而且初始化时,需要将内部iterator置于一个有效的位置。

每次调用next后,也需要将iterator更新至一个有效位置

 

代码:

class Vector2D {
public:
    Vector2D(vector<vector<int>>& vec2d) {
        for(auto v : vec2d){
            for(auto n : v){
                q.push(n);
            }
        }    
    }

    int next() {
        int ret = q.front();
        q.pop();
        return ret;
    }

    bool hasNext() {
        return !q.empty();
    }
private:
    queue<int> q;
};

/**
 * Your Vector2D object will be instantiated and called as such:
 * Vector2D i(vec2d);
 * while (i.hasNext()) cout << i.next();
 */

使用iter:

class Vector2D {
public:
    Vector2D(vector<vector<int>>& vec2d) {
        //local_v = vec2d;
        m_iter = vec2d.begin();
        m_end = vec2d.end();
        if(m_iter != m_end){
            sub_iter = (*m_iter).begin();
            while(sub_iter == (*m_iter).end()){
                m_iter++;
                if(m_iter != m_end)
                    sub_iter = (*m_iter).begin();
                else break;
            }
        }
    }

    int next() {
        int ret;
        ret = *sub_iter;
        sub_iter++;
        while(sub_iter == (*m_iter).end()){
            m_iter++;
            if(m_iter != m_end) sub_iter = (*m_iter).begin();
            else break;
        }
        
        return ret;
    }

    bool hasNext() {
        
        if(m_iter == m_end) return false;
        return true;
    }
private:
    vector<vector<int>>::iterator m_iter, m_end;
    vector<int>::iterator sub_iter;
    //vector<vector<int>> local_v;
};

/**
 * Your Vector2D object will be instantiated and called as such:
 * Vector2D i(vec2d);
 * while (i.hasNext()) cout << i.next();
 */

 

转载于:https://www.cnblogs.com/yaoyudadudu/p/9425213.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值