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
public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0) {
return new int[0];
}
Set<Integer> result = new HashSet<>();
Map<Integer, Integer> map = new HashMap<>();
Arrays.stream(nums1).forEach(
item -> {
map.merge(item, 1, (a, b) -> a + b);
}
);
for (int num : nums2) {
if (map.containsKey(num)) {
result.add(num);
map.merge(num, 1, (a, b) -> a - b);
if (map.get(num) == 0) {
map.remove(num);
}
}
}
List<Integer> result1 = result.stream().collect(Collectors.toList());
int[] resultArray = new int[result.size()];
for (int i = 0; i < result.size(); i++) {
resultArray[i] = result1.get(i);
}
return resultArray;
}
}