349. Intersection of Two Arrays

LeetCode easy original: C# #array #backtracking #csharp #easy #hash-table #leetcode
選択した UI 言語に合わせて問題文をロシア語から翻訳します。コードは変更しません。

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 表示.

すべての求人
有効な求人はまだありません。