C++ 中的交错迭代器
假设有两个一维数组,我们需要实现一个可以交替返回其元素的迭代器。这里将有两种方法 −
next() − 获取下一个元素
hasNext() − 检查下一个元素是否存在。
因此,如果输入类似 v1 = [1,2] v2 = [3,4,5,6],则输出将是 [1,3,2,4,5,6]
为了解决这个问题,我们将按照以下步骤操作 −
定义一个对 q 的队列
从初始化程序中获取两个数组 v1 和 v2,
如果 v1 的大小,则 −
将 { 0, 0} 插入 q
如果 v2 的大小,则 −
将 { 0, 1} 插入 q
定义一个成对的临时 temp
temp := q 的第一个元素
从 q 中删除元素
ret := 0
如果 temp.second 与 1 相同,则 −
ret := v2[temp.first]
(将 temp.first 增加 1)
如果 temp.first < v2 的大小,则 −
将 temp 插入 q
否则
ret := v1[temp.first]
(将 temp.first 增加 1)
如果 temp.first < v1 的大小,则 −
将 temp 插入 q
返回 ret
定义一个函数 hasNext()
当 q 不为空时,返回 true
示例
让我们看一下以下实现,以便更好地理解 −
#include <bits/stdc++.h>
using namespace std;
class ZigzagIterator {
public:
queue <pair<int, int>> q;
vector <int< v1, v2;
ZigzagIterator(vector<int<& v1, vector<int<& v2) {
this->v1 = v1;
this->v2 = v2;
if (v1.size()) {
q.push({ 0, 0 });
}
if (v2.size()) {
q.push({ 0, 1 });
}
}
int next() {
pair<int, int> temp;
temp = q.front();
q.pop();
int ret = 0;
if (temp.second == 1) {
ret = v2[temp.first];
temp.first++;
if (temp.first < v2.size())
q.push(temp);
}
else {
ret = v1[temp.first];
temp.first++;
if (temp.first < v1.size())
q.push(temp);
}
return ret;
}
bool hasNext() {
return !q.empty();
}
};
main(){
vector<int< v1 = {1,3,5,7}, v2 = {2,4,6,8,10,12,17};
ZigzagIterator ob(v1, v2);
cout << (ob.next()) << endl;
cout << (ob.next()) << endl;
cout << (ob.hasNext() ? "True" : "False") << endl;
cout << (ob.next()) << endl;
cout << (ob.next()) << endl;
cout << (ob.next()) << endl;
cout << (ob.hasNext() ? "True" : "False") << endl;
cout << (ob.next()) << endl;
cout << (ob.next()) << endl;
cout << (ob.next()) << endl;
cout << (ob.next()) << endl;
cout << (ob.hasNext() ? "True" : "False") << endl;
cout << (ob.next()) << endl;
cout << (ob.next()) << endl;
cout << (ob.hasNext() ? "True" : "False") << endl;
}输入
{1,3,5,7},{2,4,6,8,10,12,17}输出
1 2 True 3 4 5 True 6 7 8 10 True 12 17 False
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP