Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

349. 两个数组的交集 #69

Open
Geekhyt opened this issue Sep 15, 2021 · 0 comments
Open

349. 两个数组的交集 #69

Geekhyt opened this issue Sep 15, 2021 · 0 comments
Labels

Comments

@Geekhyt
Copy link
Owner

Geekhyt commented Sep 15, 2021

原题链接

借用 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 Geekhyt added the 简单 label Sep 15, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant