350 Intersection of Two Arrays II

1. Question

Given two arrays, write a function to compute their intersection.
Example: Givennums1=[1, 2, 2, 1],nums2=[2, 2], return[2, 2].
Note:
  • Each element in the result should appear as many times as it shows in both arrays.
  • The result can be in any order.
Follow up:
  • What if the given array is already sorted? How would you optimize your algorithm?
  • What if nums1's size is small compared to nums2's size? Which algorithm is better?
  • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

2. Implementation

(1) Two Pointers
1
class Solution {
2
public int[] intersect(int[] nums1, int[] nums2) {
3
Arrays.sort(nums1);
4
Arrays.sort(nums2);
5
6
List<Integer> list = new ArrayList<>();
7
8
int i = 0, j = 0;
9
10
while (i < nums1.length && j < nums2.length) {
11
if (nums1[i] < nums2[j]) {
12
++i;
13
}
14
else if (nums1[i] > nums2[j]) {
15
++j;
16
}
17
else {
18
list.add(nums1[i]);
19
++i;
20
++j;
21
}
22
}
23
24
int[] res = new int[list.size()];
25
int index = 0;
26
27
for (int e : list) {
28
res[index++] = e;
29
}
30
return res;
31
}
32
}
Copied!
(2) Binary Search
1
class Solution {
2
public int[] intersect(int[] nums1, int[] nums2) {
3
if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
4
return new int[0];
5
}
6
7
if (nums1.length < nums2.length) {
8
return getIntersection(nums1, nums2);
9
}
10
else {
11
return getIntersection(nums2, nums1);
12
}
13
}
14
15
public int[] getIntersection(int[] nums1, int[] nums2) {
16
List<Integer> list = new ArrayList<>();
17
List<Integer> intersection = new ArrayList<>();
18
19
Arrays.sort(nums2);
20
21
for (int num : nums2) {
22
list.add(num);
23
}
24
25
for (int i = 0; i < nums1.length; i++) {
26
int searchIndex = binarySearch(list, nums1[i]);
27
28
if (searchIndex != -1) {
29
intersection.add(nums1[i]);
30
list.remove(searchIndex);
31
}
32
}
33
34
int[] res = new int[intersection.size()];
35
int index = 0;
36
37
for (int e : intersection) {
38
res[index++] = e;
39
}
40
return res;
41
}
42
43
public int binarySearch(List<Integer> list, int target) {
44
int start = 0, end = list.size() - 1, mid = 0;
45
46
while (start <= end) {
47
mid = start + (end - start) / 2;
48
49
if (list.get(mid) == target) {
50
return mid;
51
}
52
else if (list.get(mid) < target) {
53
start = mid + 1;
54
}
55
else {
56
end = mid - 1;
57
}
58
}
59
return -1;
60
}
61
}
Copied!

3. Time & Space Complexity

Two Pointers: 时间复杂度O(nlogn + mlogm),n为nums1的长度, m为nums2的长度,空间复杂度O(Math.min(m,n))
Binary Search: 时间复杂度O(nlogn + mlogn), m为num1的长度, n为nums2的长度,空间复杂度O(Math.min(m,n))