두 개의 1D 배열이 있다고 가정하고 요소를 교대로 반환하는 반복자를 구현해야 합니다. 두 가지 방법이 있습니다 -
-
next() - 다음 요소를 가져오기 위해
-
hasNext() - 다음 요소가 있는지 여부를 확인합니다.
따라서 입력이 v1 =[1,2] v2 =[3,4,5,6] 이면 출력은 [1,3,2,4,5,6],
이 문제를 해결하기 위해 다음 단계를 따릅니다. −
-
쌍의 하나의 대기열 q 정의
-
이니셜라이저에서 두 개의 배열 v1 및 v2를 가져옵니다.
-
크기가 v1이면 -
-
q에 { 0, 0 } 삽입
-
-
크기가 v2인 경우 -
-
q에 { 0, 1 } 삽입
-
-
한 쌍의 온도 정의
-
temp :=q의 첫 번째 요소
-
q에서 요소 삭제
-
ret :=0
-
temp.second가 1과 같으면 -
-
ret :=v2[temp.first]
-
(temp.first를 1씩 증가)
-
temp.first
-
q에 temp 삽입
-
-
-
그렇지 않으면
-
ret :=v1[temp.first]
-
(temp.first를 1씩 증가)
-
temp.first
-
q에 temp 삽입
-
-
-
리턴 렛
-
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