假设有两个一维数组,我们必须实现一个迭代器,该迭代器将交替返回其元素。将有两种方法-
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:= q的第一个元素
从q删除元素
ret:= 0
如果temp.second与1相同,则-
将温度插入q
ret:= v2 [temp.first]
(首先将温度升高1)
如果temp.first <v2的大小,则-
除此以外
将温度插入q
ret:= v1 [temp.first]
(首先将温度升高1)
如果temp.first <v1的大小,则-
返回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