349. Intersection of Two Arrays

Set

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<>();
for (int num : nums1) {
set1.add(num);
}

Set<Integer> set2 = new HashSet<>();
for (int num : nums2) {
set2.add(num);
}

set1.retainAll(set2);

int[] ans = new int[set1.size()];
int i = 0;
for (int num : set1) {
ans[i++] = num;
}
return ans;
}
}

Two Pointers

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
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);

List<Integer> list = new ArrayList<>();
int index1 = 0, index2 = 0, targetIndex = 0;
while (index1 < nums1.length && index2 < nums2.length) {
int num1 = nums1[index1];
int num2 = nums2[index2];

if (num1 < num2) {
index1++;
} else if (num1 > num2) {
index2++;
} else {
if (targetIndex == 0 || list.get(targetIndex - 1) != num1) {
list.add(num1);
targetIndex++;
}

index1++;
index2++;
}
}

int[] array = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
array[i] = list.get(i);
}
return array;
}
}

References

349. Intersection of Two Arrays