Intersection of Two Arrays

Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].

Note:

  1. Each element in the result must be unique.
  2. The result can be in any order.

solutions

Python

1
2
3
4
5
6
7
8
9
10
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
nums1 = set(nums1)
nums2 = set(nums2)
return list(nums1&nums2)

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
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
public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set = new HashSet<>();
Arrays.sort(nums2);
for (Integer num: nums1) {
if (binarySearch(nums2, num)) {
set.add(num);
}
}
int i = 0;
int[] res = new int[set.size()];
for (Integer num : set) {
res[i++] = num;
}
return res;
}

public boolean binarySearch(int[] nums, int target) {
int low = 0;
int high = nums.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (nums[mid] == target) {
return true;
}
if (nums[mid] > target) {
high = mid - 1;
} else{
low = mid + 1;
}
}
return false;
}
}




// recommended
public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums2 == null) {
return null;
}

Arrays.sort(nums1);
Arrays.sort(nums2);
int i = 0, j = 0, index = 0;
int[] temp = new int[nums1.length];
while (i < nums1.length && j < nums2.length) {
if (nums1[i] == nums2 [j]) {
if (index == 0 || temp[index - 1] != nums1[i]) {
temp[index] = nums1[i];
index ++;
}
i ++;
j ++;
} else if (nums1[i] < nums2[j]){
i ++;
} else {
j ++;
}
}
int[] result = new int[index];
for(int k = 0; k < index; k++) {
result[k] = temp[k];
}
return result;
}
}