349.Intersection of Two Arrays

Solution 1: accepted 5ms

Time: O(n) 2*(m+n)
Space: O(n) m+n

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