-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntersectionOfTwoArrays.java
More file actions
59 lines (51 loc) · 1.26 KB
/
IntersectionOfTwoArrays.java
File metadata and controls
59 lines (51 loc) · 1.26 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
import java.util.*;
class IntersectionOfTwoArrays
{
public static int[] intersection(int[] nums1, int[] nums2)
{
int n1 = nums1.length;
int n2 = nums2.length;
int [] countarr=new int [1001];
for (int i=0;i<n1;i++)
{
countarr[nums1[i]]++;
}
List <Integer> ans = new ArrayList<>();
for (int i=0;i<n2;i++)
{
if (countarr[nums2[i]] > 0)
{
ans.add(nums2[i]);
countarr[nums2[i]]=0;
}
}
return listToArray(ans);
}
public static int [] listToArray(List<Integer> ans)
{
int n = ans.size();
int []arr= new int [n];
for (int i=0;i<n;i++)
{
arr[i]=ans.get(i);
}
return arr;
}
public static void main(String []args)
{
Scanner sc = new Scanner (System.in);
int n=sc.nextInt();
int m=sc.nextInt();
int [] nums1 = new int [n];
int [] nums2 = new int [m];
for (int i = 0;i<n;i++)
{
nums1[i]=sc.nextInt();
}
for (int i = 0;i<m;i++)
{
nums2[i]=sc.nextInt();
}
System.out.println(intersection( nums1, nums2));
}
}