350.Intersection of Two Arrays II

Solution 1: accepted 4ms

Two pointers. Since the value could be duplicated, binary search is not the best shot.

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
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
int i = 0;
int j = 0;
List<Integer> list = new ArrayList<>();
while (i < nums1.length && j < nums2.length) {
if (nums1[i] > nums2[j]) {
j++;
} else if (nums1[i] < nums2[j]) {
i++;
} else {
list.add(nums1[i]);
i++;
j++;
}
}
int[] result = new int[list.size()];
int k = 0;
for(Integer n : list) {
result[k++] = n;
}
return result;
}
}