-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathUnion_Intersection_Array.java
More file actions
61 lines (53 loc) · 1.47 KB
/
Copy pathUnion_Intersection_Array.java
File metadata and controls
61 lines (53 loc) · 1.47 KB
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
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;
public class Union_Intersection_Array {
static void union(int a[],int n,int b[],int m) {
HashSet<Integer> hs=new HashSet<>(m+n);
for (int i = 0; i < n; i++)
hs.add(a[i]);
for (int i = 0; i < m; i++)
hs.add(b[i]);
Iterator<Integer> itr = hs.iterator();
while (itr.hasNext()) {
System.out.print(itr.next()+" ");
}
System.out.println();
System.out.println(hs.size());
}
static void intersection(int a[],int n,int b[],int m) {
HashSet<Integer> hs1=new HashSet<>(m+n);
for (int i = 0; i < n; i++)
hs1.add(a[i]);
int count=0;
for (int i = 0; i < m; i++) {
if(hs1.contains(b[i])) {
count++;
System.out.print(b[i]+" ");
hs1.remove(b[i]);
}
}
System.out.println();
System.out.println(count);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
// Given two unsorted arrays that represent two sets (elements in every array are distinct)
// find the union and intersection of two arrays.
Scanner s=new Scanner(System.in);
int n,m;
n=s.nextInt();
int [] a= new int[n];
for (int i = 0; i < n; i++) {
a[i]=s.nextInt();
}
m=s.nextInt();
int [] b= new int[n];
for (int i = 0; i < m; i++) {
b[i]=s.nextInt();
}
union(a,n,b,m);
intersection(a,n,b,m);
s.close();
}
}