Given two arrays, write a function to compute their intersection.
求两个数组的交集
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Note:
Each element in the result should appear as many times as it shows in both arrays.
结果中的每个元素都应该出现在两个数组中的多次
The result can be in any order.
结果可以是任何顺序
Follow up:
What if the given array is already sorted? How would you optimize your algorithm?
What if nums1’s size is small compared to nums2’s size? Which algorithm is better?
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
解题思路:使用map存储第一个数组value:值的数目,遍历第二个数组,若存在map内,取出
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number[]}
*/
var intersect = function(nums1, nums2) {
var map = {}
nums1.map((cur) => {
if (map[cur] === undefined) {
map[cur] = 1
} else {
map[cur] += 1
}
})
var returnArray = []
nums2.map((cur) => {
if (map[cur] > 0) {
map[cur] -= 1
returnArray.push(cur)
}
})
return returnArray
};