← Static tasks

350. Intersection of Two Arrays II

leetcode easy

#array#backtracking#csharp#easy#hash-table#leetcode

Task

Даны два целочисленных массива nums1 и nums2. Верните массив их пересечения. Каждый элемент в результате должен появляться столько раз, сколько он встречается в обоих массивах. Вы можете вернуть результат в любом порядке.

Пример

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

Output: [2,2]

C# solution

matched/original
public class Solution {
    public int[] Intersect(int[] nums1, int[] nums2) {
        Dictionary<int, int> counts = new Dictionary<int, int>();
        List<int> result = new List<int>();
        
        foreach (int num in nums1) {
            if (counts.ContainsKey(num)) {
                counts[num]++;
            } else {
                counts[num] = 1;
            }
        }
        
        foreach (int num in nums2) {
            if (counts.ContainsKey(num) && counts[num] > 0) {
                result.Add(num);
                counts[num]--;
            }
        }
        
        return result.ToArray();
    }
}

C++ solution

auto-draft, review before submit
#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>& Intersect(vector<int>& nums1, vector<int>& nums2) {
        unordered_map<int, int> counts = new unordered_map<int, int>();
        List<int> result = new List<int>();
        
        foreach (int num in nums1) {
            if (counts.count(num)) {
                counts[num]++;
            } else {
                counts[num] = 1;
            }
        }
        
        foreach (int num in nums2) {
            if (counts.count(num) && counts[num] > 0) {
                result.push_back(num);
                counts[num]--;
            }
        }
        
        return result.ToArray();
    }
}

Java solution

auto-draft, review before submit
import java.util.*;
import java.math.*;

// Auto-generated Java draft from the C# solution. Review API differences before LeetCode submit.
public class Solution {
    public int[] Intersect(int[] nums1, int[] nums2) {
        HashMap<int, int> counts = new HashMap<int, int>();
        List<int> result = new List<int>();
        
        foreach (int num in nums1) {
            if (counts.containsKey(num)) {
                counts[num]++;
            } else {
                counts[num] = 1;
            }
        }
        
        foreach (int num in nums2) {
            if (counts.containsKey(num) && counts[num] > 0) {
                result.add(num);
                counts[num]--;
            }
        }
        
        return result.ToArray();
    }
}

JavaScript solution

matched/original
var intersect = function(nums1, nums2) {
    let counts = {};
    let result = [];
    
    for (let num of nums1) {
        counts[num] = (counts[num] || 0) + 1;
    }
    
    for (let num of nums2) {
        if (counts[num] > 0) {
            result.push(num);
            counts[num]--;
        }
    }
    
    return result;
};

Python solution

matched/original
from collections import Counter

class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        counts = Counter(nums1)
        result = []

        for num in nums2:
            if counts[num] > 0:
                result.append(num)
                counts[num] -= 1

        return result

Go solution

matched/original
func intersect(nums1 []int, nums2 []int) []int {
    counts := make(map[int]int)
    var result []int
    
    for _, num := range nums1 {
        counts[num]++
    }
    
    for _, num := range nums2 {
        if counts[num] > 0 {
            result = append(result, num)
            counts[num]--
        }
    }
    
    return result
}

Explanation

Algorithm

Подсчет частоты элементов:

Используйте хеш-таблицу или словарь для подсчета количества вхождений каждого элемента в nums1.

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

Пройдите по элементам nums2, и если элемент присутствует в хеш-таблице из шага 1 и его счетчик больше нуля, добавьте этот элемент в результат и уменьшите счетчик.

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

Верните массив пересечения.

😎