-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntersectionofTwoArrays.java
More file actions
40 lines (35 loc) · 1.04 KB
/
IntersectionofTwoArrays.java
File metadata and controls
40 lines (35 loc) · 1.04 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
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
public class IntersectionofTwoArrays {
public static void main(String[] args) {
int[] nums1 = {1,2,3,4};
int[] nums2 = {2,2,3};
int[] result = intersection(nums1, nums2);
// Printing the intersection elements
System.out.print("Intersection: ");
for (int num : result) {
System.out.print(num + " ");
}
}
public static int[] intersection(int[] nums1, int[] nums2) {
HashSet<Integer> set = new HashSet<>();
HashSet<Integer> ans = new HashSet<>();
for (int i = 0; i < nums1.length; i++) {
set.add(nums1[i]);
}
for (int i = 0; i < nums2.length ; i++) {
if(set.contains(nums2[i])){
ans.add(nums2[i]);
}
}
int[] aans = new int[ans.size()];
int index = 0;
for (int num : ans) {
aans[index] = num;
index++;
}
return aans;
}
}