Intersection of Two Arrays [LeetCode Top Interview Questions Series]
One way to solve this problem is to use a hash set to store the elements of one of the arrays and then use a loop to check if each element of the other array is in the hash set. If it is, we add it to the result and remove it from the hash set so that we don’t count duplicates.
Here’s an example implementation in Java:
public class Test {
public static void main(String[] args) {
int[] nums1 = {4,9,5};
int[] nums2 = {9,4,9,8,4};
Map<Integer, Integer> map = new HashMap<>();
for (int num : nums1) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
List<Integer> result = new ArrayList<>();
for (int num : nums2) {
if (map.containsKey(num) && map.get(num) > 0) {
result.add(num);
map.put(num, map.get(num) - 1);
}
}
int[] res = new int[result.size()];
for (int i = 0; i < result.size(); i++) {
res[i] = result.get(i);
}
System.out.println(res);
}
}
In this implementation, we first use a HashMap
to store the elements of the first array nums1
and their count. Then, we loop through the second array nums2
, and if the current element is in the HashMap
and its count is greater than 0, we add it to the result list and decrease its count in the HashMap
. Finally, we convert the result list to an array and return it.
The time complexity of this solution is O(m + n), where m and n are the number of elements in nums1
and nums2
, respectively, since we need to examine all the elements in both arrays. The space complexity is O(min(m, n)), since the size of the HashMap
and the result list is proportional to the size of the smaller array.