# [LeetCode] Zigzag Iterator 之字形迭代器

+关注继续查看

Given two 1d vectors, implement an iterator to return their elements alternately.

For example, given two 1d vectors:

v1 = [1, 2]
v2 = [3, 4, 5, 6]


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

Follow up: What if you are given k 1d vectors? How well can your code be extended to such cases?

Clarification for the follow up question - Update (2015-09-18):
The "Zigzag" order is not clearly defined and is ambiguous for k > 2 cases. If "Zigzag" does not look right to you, replace "Zigzag" with "Cyclic". For example, given the following input:

[1,2,3]
[4,5,6,7]
[8,9]


It should return [1,4,8,2,5,9,3,6,7].

class ZigzagIterator {
public:
ZigzagIterator(vector<int>& v1, vector<int>& v2) {
v.push_back(v1);
v.push_back(v2);
i = j = 0;
}
int next() {
return i <= j ? v[0][i++] : v[1][j++];
}
bool hasNext() {
if (i >= v[0].size()) i = INT_MAX;
if (j >= v[1].size()) j = INT_MAX;
return i < v[0].size() || j < v[1].size();
}
private:
vector<vector<int>> v;
int i, j;
};

class ZigzagIterator {
public:
ZigzagIterator(vector<int>& v1, vector<int>& v2) {
int n1 = v1.size(), n2 = v2.size(), n = max(n1, n2);
for (int i = 0; i < n; ++i) {
if (i < n1) v.push_back(v1[i]);
if (i < n2) v.push_back(v2[i]);
}
}
int next() {
return v[i++];
}
bool hasNext() {
return i < v.size();
}
private:
vector<int> v;
int i = 0;
};

class ZigzagIterator {
public:
ZigzagIterator(vector<int>& v1, vector<int>& v2) {
if (!v1.empty()) q.push(make_pair(v1.begin(), v1.end()));
if (!v2.empty()) q.push(make_pair(v2.begin(), v2.end()));
}
int next() {
auto it = q.front().first, end = q.front().second;
q.pop();
if (it + 1 != end) q.push(make_pair(it + 1, end));
return *it;
}
bool hasNext() {
return !q.empty();
}
private:
queue<pair<vector<int>::iterator, vector<int>::iterator>> q;
};

10027 0
python3中的迭代器与生成器

772 0
python设计模式（十七）：迭代器模式——迭代器与生成器

1074 0

13841 0
[leetcode/lintcode 题解]算法面试真题详解：左旋右旋迭代器
[leetcode/lintcode 题解]算法面试真题详解：左旋右旋迭代器
71 0
Python基础教程第二版 9:魔法方法,属性,迭代器(未完)
python基础教程第二版 9 :魔法方法,属性,迭代器 新类与旧类 构造方法:对象被创建后立即执行的方法 __init__     class 类名:         def __init__(self):             self.
662 0
javascript中的迭代器
1.forEach迭代器 forEach方法接收一个函数作为参数，对数组中每个元素使用这个函数，只调用这个函数，数组本身没有任何变化 //forEach迭代器 function square(num){ document.
733 0
+关注

2107

1103

《2021云上架构与运维峰会演讲合集》

《零基础CSS入门教程》

《零基础HTML入门教程》