-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintersect.java
More file actions
37 lines (32 loc) · 1.03 KB
/
intersect.java
File metadata and controls
37 lines (32 loc) · 1.03 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
import java.util.*;
public class intersect{
public static void main(String args[]){
int nums1[]={1,2,2,3,3,4};
int nums2[]={2,3,4,5,6};
int result[]=intersect_arrays(nums1,nums2);
System.out.println(Arrays.toString(result));
}
public static int[] intersect_arrays(int[] nums1, int[] nums2) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
ArrayList<Integer> result = new ArrayList<Integer>();
for(int i = 0; i < nums1.length; i++)
{
if(map.containsKey(nums1[i])) map.put(nums1[i], map.get(nums1[i])+1);
else map.put(nums1[i], 1);
}
for(int i = 0; i < nums2.length; i++)
{
if(map.containsKey(nums2[i]) && map.get(nums2[i]) > 0)
{
result.add(nums2[i]);
map.put(nums2[i], map.get(nums2[i])-1);
}
}
int[] r = new int[result.size()];
for(int i = 0; i < result.size(); i++)
{
r[i] = result.get(i);
}
return r;
}
}