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:

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

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class {
public int[] intersection(int[] nums1, int[] nums2) {
List<Integer> list = new ArrayList<>();
for(int i=0; i<nums1.length;i++) {
if(!list.contains(nums1[i])) {
list.add(nums1[i]);
}
}
List<Integer> result = new ArrayList<>();
for(int i=0; i<nums2.length; i++) {
if(list.contains(nums2[i]) && !result.contains(nums2[i])) {
result.add(nums2[i]);
}
}
int[] re = new int[result.size()];
for(int i=0; i<result.size(); i++) {
re[i] = result.get(i);
}
return re;
}
}