-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIntersection of Two arrays with duplicate elements.cpp
64 lines (55 loc) · 1.35 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
//{ 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
unordered_set<int> st(a.begin(),a.end());
unordered_set<int> ans;
for(int i:b)
{
if(st.erase(i)){
ans.insert(i);
}
}
return vector<int>(ans.begin(),ans.end());
}
};
//{ 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