-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIntersection of Two arrays with Duplicate Elements.cpp
73 lines (62 loc) · 1.62 KB
/
Intersection of Two arrays with Duplicate 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution {
public:
vector<int> intersectionWithDuplicates(vector<int>& a, vector<int>& b) {
// code here
sort(a.begin(), a.end());
sort(b.begin(), b.end());
int i = 0, j = 0;
int n1 = a.size(), n2 = b.size();
vector<int> result;
while(i<n1 && j<n2){
if(a[i] < b[j]) i++;
else if(a[i] > b[j]) j++;
else{
auto it = find(result.begin(), result.end(), a[i]);
if(it == result.end()) result.push_back(a[i]);
i++;
j++;
}
}
return result;
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
cin.ignore();
while (t--) {
vector<int> arr1, arr2;
string input;
// Read first array
getline(cin, input);
stringstream ss(input);
int number;
while (ss >> number) {
arr1.push_back(number);
}
// Read second array
getline(cin, input);
stringstream ss2(input);
while (ss2 >> number) {
arr2.push_back(number);
}
Solution ob;
vector<int> res = ob.intersectionWithDuplicates(arr1, arr2);
sort(res.begin(), res.end());
if (res.size() == 0) {
cout << "[]" << endl;
} else {
for (auto it : res)
cout << it << " ";
cout << endl;
}
cout << "~" << endl;
}
return 0;
}
// } Driver Code Ends