javascript-leetcode icon indicating copy to clipboard operation
javascript-leetcode copied to clipboard

349. 两个数组的交集

Open Geekhyt opened this issue 4 years ago • 0 comments

原题链接

借用 Map

  1. 先明确题意,题目让我们求交集,也就是两个数组共有的元素
  2. 借用 Map,遍历 nums1,将 nums1 中的元素作为 key,value 都设置为 true 填充 Map
  3. 遍历 nums2,如果在 map 中出现过,也就是说在 nums1 中出现过,就是他们共有的元素,push 进 res,从 map 中删除。
  4. 最后返回 res 即可
const intersection = function(nums1, nums2) {
    const map = new Map()
    const res = []
    nums1.forEach(n => {
        map.set(n, true)
    })
    nums2.forEach(n => {
        if (map.get(n)) {
            res.push(n)
            map.delete(n)
        }
    })
    return res
}
  • 时间复杂度: O(m + n)
  • 空间复杂度: O(m)

Geekhyt avatar Sep 15 '21 10:09 Geekhyt