forked from reachanihere/Data-Structures-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Print Intersection.cpp
105 lines (78 loc) · 1.78 KB
/
Print Intersection.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
97
98
99
100
101
102
103
104
105
/*
Given two random integer arrays, print their intersection. That is, print all the elements that are present in both the given arrays.
Input arrays can contain duplicate elements.
Note : Order of elements are not important
Input format :
Line 1 : Integer N, Array 1 Size
Line 2 : Array 1 elements (separated by space)
Line 3 : Integer M, Array 2 Size
Line 4 : Array 2 elements (separated by space)
Output format :
Print intersection elements in different lines
Constraints :
1 <= M, N <= 10^6
Sample Input 1 :
6
2 6 8 5 4 3
4
2 3 4 7
Sample Output 1 :
2
4
3
Sample Input 2 :
4
2 6 1 2
5
1 2 3 4 2
Sample Output 2 :
2
2
1
*/
// input1 - first array
// input2 - second array
// size1 - size of first array
// size2 - size of second array
#include <bits/stdc++.h>
using namespace std;
void intersection(int input1[], int input2[], int size1, int size2) {
/* Don't write main().
* Don't read input, it is passed as function argument.
* Print the output and don't return it.
* Taking input is handled automatically.
*/
unordered_map<int,int> m;
for(int i=0;i<size1;i++){
if (m.count(input1[i])==0)
m[input1[i]]=1;
else
m[input1[i]]+=1;
}
for(int i=0;i<size2;i++){
if(m.count(input2[i])==1){
if(m[input2[i]]==0)
continue;
cout<<input2[i]<<endl;
m[input2[i]]-=1;
}
}
}
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;
#include "solution.h"
int main() {
int size1,size2;
cin>>size1;
int *input1=new int[1+size1];
for(int i=0;i<size1;i++)
cin>>input1[i];
cin>>size2;
int *input2=new int[1+size2];
for(int i=0;i<size2;i++)
cin>>input2[i];
intersection(input1,input2,size1,size2);
return 0;
}