-
Notifications
You must be signed in to change notification settings - Fork 117
Expand file tree
/
Copy pathIntersectionOfTwoArrays349.java
More file actions
71 lines (61 loc) · 1.75 KB
/
IntersectionOfTwoArrays349.java
File metadata and controls
71 lines (61 loc) · 1.75 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
62
63
64
65
66
67
68
69
70
71
/**
* Given two arrays, write a function to compute their intersection.
*
* Example:
* Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
*
* Note:
* Each element in the result must be unique.
* The result can be in any order.
*/
import java.util.Set;
import java.util.HashSet;
public class IntersectionOfTwoArrays349 {
public static int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums1.length == 0 ||
nums2 == null || nums2.length == 0) return new int[]{};
Set<Integer> setNums1 = new HashSet<>();
for (int i1: nums1) {
setNums1.add(i1);
}
Set<Integer> resSet = new HashSet<>();
for (int i2: nums2) {
if (setNums1.contains(i2)) {
resSet.add(i2);
}
}
int[] res = new int[resSet.size()];
int i = 0;
for (Integer resInt: resSet) {
res[i++] = (int) resInt;
}
return res;
}
/**
* https://leetcode.com/problems/intersection-of-two-arrays/discuss/81969/Three-Java-Solutions
*/
public int[] intersection2(int[] nums1, int[] nums2) {
Set<Integer> set = new HashSet<>();
Arrays.sort(nums1);
Arrays.sort(nums2);
int i = 0;
int j = 0;
while (i < nums1.length && j < nums2.length) {
if (nums1[i] < nums2[j]) {
i++;
} else if (nums1[i] > nums2[j]) {
j++;
} else {
set.add(nums1[i]);
i++;
j++;
}
}
int[] result = new int[set.size()];
int k = 0;
for (Integer num : set) {
result[k++] = num;
}
return result;
}
}