Intersection of two arrays II
Given two arrays, write a function to calculate their intersection.
Example 1:
Enter: nums1 = [1.2.2.1], nums2 = [2.2] output: [2.2]
Copy the code
Example 2:
Enter: nums1 = [4.9.5], nums2 = [9.4.9.8.4] output: [4.9]
Copy the code
Description:
The number of occurrences of each element in the output should be the same as the minimum number of occurrences of the element in both arrays. We can ignore the order of the output.Copy the code
Advanced:
What if the given array is already sorted? How will you optimize your algorithm? If nums1 is much smaller than NUMs2, which method is better? What do you do if nums2 elements are stored on disk, memory is limited, and you can't load all elements into memory at once?Copy the code
/ * * *@param {number[]} nums1
* @param {number[]} nums2
* @return {number[]}* /
var intersect = function (nums1, nums2) {
let ans = [] / / the result
for(let i =0; i<nums1.length; i++){let sub = nums2.indexOf(nums1[i]) // find the index of nums1[I] in nums2
if(sub>-1){
ans.push(nums1[i])
nums2.splice(sub,1) // delete nums1[I]}}return ans
};
Copy the code
Intersection of two arrays (unique value)
/** Hash the intersection of two arrays */
/ * * *@param {number[]} nums1
* @param {number[]} nums2
* @return {number[]}* /
var intersect = function (nums1, nums2) {
let ans = [], hash = {}
for (let i of nums1) {
hash[i] ? ++hash[i] : hash[i] = 1 // Count the number of occurrences
}
for (let j in nums2) {
if (hash[j]) { // Make a comparison
ans.push(j)
--hash[j] // The contrast is reduced}}return ans
};
Copy the code