349. Intersection of Two Arrays

LeetCode easy original: C# #array #backtracking #csharp #easy #hash-table #leetcode
题目文本会按所选界面语言从俄语翻译;代码保持不变。

given два целочисленных 数组а nums1 и nums2. return 数组 их пересечения. Каждый element в результате должен быть уникальным, и вы можете вернуть результат в любом порядке.

示例

Input: nums1 = [1,2,2,1], nums2 = [2,2]

Output: [2]

C# 解法

匹配/原始
public class Solution {
    public int[] Intersection(int[] nums1, int[] nums2) {
        HashSet<int> set1 = new HashSet<int>(nums1);
        HashSet<int> set2 = new HashSet<int>(nums2);
        set1.IntersectWith(set2);
        int[] result = new int[set1.Count];
        set1.CopyTo(result);
        return result;
    }
}

C++ 解法

自动草稿,提交前请检查
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    public vector<int>& Intersection(vector<int>& nums1, vector<int>& nums2) {
        HashSet<int> set1 = new HashSet<int>(nums1);
        HashSet<int> set2 = new HashSet<int>(nums2);
        set1.IntersectWith(set2);
        vector<int>& result = new int[set1.size()];
        set1.CopyTo(result);
        return result;
    }
}

Java 解法

匹配/原始
public class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set1 = new HashSet<>();
        for (int num : nums1) {
            set1.add(num);
        }
        Set<Integer> set2 = new HashSet<>();
        for (int num : nums2) {
            set2.add(num);
        }
        set1.retainAll(set2);
        int[] result = new int[set1.size()];
        int i = 0;
        for (int num : set1) {
            result[i++] = num;
        }
        return result;
    }
}

JavaScript 解法

匹配/原始
var intersection = function(nums1, nums2) {
    let set1 = new Set(nums1);
    let set2 = new Set(nums2);
    let result = [];

    for (let num of set1) {
        if (set2.has(num)) {
            result.push(num);
        }
    }
    
    return result;
};

Algorithm

Создание множеств:

Преобразуйте оба 数组а nums1 и nums2 в множества для получения уникальных elementов.

Нахождение пересечения:

find пересечение двух множеств.

Возврат результата:

Преобразуйте пересечение обратно в 数组 и return его.

😎

Vacancies for this task

活跃职位 with overlapping task tags are 已显示.

所有职位
目前还没有活跃职位。