Topic describes
Given two arrays, write a function to calculate their intersection.
Input: nums1 = [1,2,2,1], nums2 = [2,2] output: [2]
//
// 1, nums1, nums2
// 2, set up a dictionary mapping relationship, record the values in nums1
// 3, run through nums2 to find the same value as nums1
//
// 1, create a new dictionary, iterate through nums1, and populate the dictionary
// 2, iterates through nums2, selects the value in the dictionary, and deletes it from the dictionary
// VX:mike_fss888(add friends wow 😝)
/ * * *@param {number[]} nums1
* @param {number[]} nums2
* @return {number[]}* /
var intersection = function (nums1, nums2) {
const map = new Map()
nums1.forEach(n= > {
map.set(n, true)})const res = []
nums2.forEach(n= > {
if (map.get(n)) {
res.push(n)
map.delete(n)
}
})
return res
};
// Time complexity: O(m+n)
// Space complexity: O(m)
// The title is reprinted from licou official website:
// https://leetcode-cn.com/problems/intersection-of-two-arrays/
Copy the code