-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathGFG_CommonElements.cpp
96 lines (82 loc) · 2.43 KB
/
GFG_CommonElements.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
https://practice.geeksforgeeks.org/problems/common-elements1132/1/#
.Common elements
*/
// { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution
{
public:
vector <int> commonElements_1 (int A[], int B[], int C[], int n1, int n2, int n3)
{
unordered_map<int,int> acnt, bcnt, ccnt;
for(int i=0; i<n1; i++)
acnt[A[i]]++;
for(int i=0; i<n2; i++)
bcnt[B[i]]++;
for(int i=0; i<n3; i++)
ccnt[C[i]]++;
vector<int> ans;
for(int i=0; i<n1; i++)
{
if(acnt[A[i]]>0 && bcnt[A[i]]>0 && ccnt[A[i]]>0)
{
ans.push_back(A[i]);
acnt[A[i]]=0;
}
}
return ans;
}//
vector <int> commonElements (int A[], int B[], int C[], int n1, int n2, int n3)
{
int i=0, j=0, k=0;
vector<int> ans;
while(i<n1 and j<n2 and k<n3)
{
if(A[i] == B[j] and B[j] == C[k])
{
ans.push_back(A[i]);
i++; j++; k++;
}
else if(A[i] < B[j])
i++;
else if(B[j] < C[k])
j++;
else
k++;
// cout<<i<<" "<<j<<" "<<k<<endl;
while(i-1>=0 && A[i] == A[i-1])
i++;
while(j-1>=0 and B[j] == B[j-1])
j++;
while(k-1>=0 and C[k] == C[k-1])
k++;
}//while
return ans;
}//
};
// { Driver Code Starts.
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;
}
} // } Driver Code Ends