Skip to content

349. 两个数组的交集 #69

Description

@Geekhyt

原题链接

借用 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)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions