-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCommon elements.cpp
57 lines (50 loc) · 1.51 KB
/
Common elements.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector <int> commonElements (int A[], int B[], int C[], int n1, int n2, int n3)
{
vector<int> result;
int i = 0, j = 0, k = 0;
while (i < n1 && j < n2 && k < n3) {
if (A[i] == B[j] && B[j] == C[k]) {
// Found a common element
result.push_back(A[i]);
// Move all pointers to the next different element
int current = A[i];
while (i < n1 && A[i] == current) i++;
while (j < n2 && B[j] == current) j++;
while (k < n3 && C[k] == current) k++;
} else {
// Move pointers of arrays with smaller values
if (A[i] <= B[j] && A[i] <= C[k]) i++;
else if (B[j] <= A[i] && B[j] <= C[k]) j++;
else if (C[k] <= A[i] && C[k] <= B[j]) k++;
}
}
return result;
}
};
int main ()
{
int t; cin >> t;
while (t--)
{
int n1, n2, n3;
cin >> n1 >> n2 >> n3;
int A[n1];
int B[n2];
int C[n3];
for (int i = 0; i < n1; i++) cin >> A[i];
for (int i = 0; i < n2; i++) cin >> B[i];
for (int i = 0; i < n3; i++) cin >> C[i];
Solution ob;
vector <int> res = ob.commonElements (A, B, C, n1, n2, n3);
if (res.size () == 0)
cout << -1;
for (int i = 0; i < res.size (); i++)
cout << res[i] << " ";
cout << endl;
}
}