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.两个数组的交集 #43

Open
wind-jyf opened this issue May 9, 2020 · 0 comments
Open

349.两个数组的交集 #43

wind-jyf opened this issue May 9, 2020 · 0 comments
Labels

Comments

@wind-jyf
Copy link
Owner

wind-jyf commented May 9, 2020

两个数组的交集

一、题目描述

给定两个数组,编写一个函数来计算它们的交集。

示例 1:

输入: nums1 = [1,2,2,1], nums2 = [2,2]
输出: [2]

示例 2:

输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [9,4]

说明:

  • 输出结果中的每个元素一定是唯一的。
  • 我们可以不考虑输出结果的顺序。

二、解题思路

  1. 因为这道题解一定是唯一的,所以为了方便去重,可以使用集合
  2. 遍历数组进行查看即可

三、代码实现

/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number[]}
 */
var intersection = function(nums1, nums2) {
    let result = new Set();
    let set2 = new Set(nums2);
    for(let i = 0;i<nums1.length;i++){
        if(set2.has(nums1[i])){
            result.add(nums1[i]);
        }
    }
    return Array.from(result);
};

参考:


@wind-jyf wind-jyf added the 算法 label May 9, 2020
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