Given two integer arrays nums1 and nums2, return an array representing their intersection. Each element in the result should appear exactly as many times as it appears in both arrays. The result may be returned in any order.
Constraints:
nums1.length, nums2.length
nums1[i], nums2[i]
The key idea is to use a hash map to count the frequency of each element in one array, and then iterate through the second array, collecting elements that exist in the hash map while decrementing their counts. This ensures each element appears in the result exactly as many times as it appears in both arrays. By building a frequency map from nums1 and then scanning nums2, we efficiently match elements between the two arrays without needing to sort or use nested loops.
Now, let’s look at the ...
Given two integer arrays nums1 and nums2, return an array representing their intersection. Each element in the result should appear exactly as many times as it appears in both arrays. The result may be returned in any order.
Constraints:
nums1.length, nums2.length
nums1[i], nums2[i]
The key idea is to use a hash map to count the frequency of each element in one array, and then iterate through the second array, collecting elements that exist in the hash map while decrementing their counts. This ensures each element appears in the result exactly as many times as it appears in both arrays. By building a frequency map from nums1 and then scanning nums2, we efficiently match elements between the two arrays without needing to sort or use nested loops.
Now, let’s look at the ...