-
Notifications
You must be signed in to change notification settings - Fork 0
/
Common Elements.cpp
65 lines (57 loc) · 1.25 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
58
59
60
61
62
63
64
65
//{ Driver Code Starts
//Initial Template for C++
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//Back-end complete function Template for C++
class Solution{
public:
vector<int> common_element(vector<int>v1,vector<int>v2)
{
// Your code here
vector<int>ans;
map<int,int>mapping;
for(int i=0;i<v1.size();i++){
mapping[v1[i]]++;
}
for(int i=0;i<v2.size();i++){
auto it = mapping.find(v2[i]);
if(it!=mapping.end() && it->second>0){
ans.push_back(v2[i]);
it->second--;
}
}
sort(ans.begin(),ans.end());
return ans;
}
};
//{ Driver Code Starts.
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
vector<int>v1(n,0);
for(int i=0;i<n;i++)
{
cin>>v1[i];
}
int m;
cin>>m;
vector<int>v2(m,0);
for(int i=0;i<m;i++)
{
cin>>v2[i];
}
Solution ob;
vector<int>result;
result=ob.common_element(v1,v2);
for(auto i:result)
{
cout<<i<<" ";
}
cout<<endl;
}
}
// } Driver Code Ends