-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathIntersectionOfTwoArrays.java
42 lines (40 loc) · 1.09 KB
/
IntersectionOfTwoArrays.java
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
package io.ziheng.hashtable.leetcode;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* LeetCode 349. Intersection of Two Arrays
* https://leetcode.com/problems/intersection-of-two-arrays/
*/
public class IntersectionOfTwoArrays {
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums2 == null) {
return null;
}
Set<Integer> setA = new HashSet<>();
Set<Integer> setB = new HashSet<>();
for (int num : nums1) {
setA.add(num);
}
for (int num : nums2) {
setB.add(num);
}
return setIntersection(setA, setB);
}
private int[] setIntersection(Set<Integer> setA, Set<Integer> setB) {
int[] arr = new int[
setA.size() > setB.size()
? setA.size()
: setB.size()
];
int index = 0;
for (int num : setA) {
if (setB.contains(num)) {
arr[index] = num;
index++;
}
}
return Arrays.copyOf(arr, index);
}
}
/* EOF */