Intersection of Two Arrays
Question (LC.349)
Example
Input: nums1 = [1, 2, 2, 1], nums2 = [2, 2]
Return: result = [2, 2] nope need to return [2]Analysis
Hash Set
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0) {
return new int[] {};
}
Set<Integer> set1 = new HashSet<>();
for (int num : nums1) {
set1.add(num);
}
Set<Integer> result = new HashSet<>();
for (int num: nums2) {
if (set1.contains(num)) {
result.add(num);
}
}
int[] intsec = new int[result.size()];
int i = 0;
for (Integer num: result) {
intsec[i++] = num.intValue();
}
return intsec;
}Sorting and P1/P2
Binary Search
Last updated