251. Flatten 2D Vector
Posted yaoyudadudu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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(); */
以上是关于251. Flatten 2D Vector的主要内容,如果未能解决你的问题,请参考以下文章