In this Leetcode Intersection of Two Arrays problem solution you have given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.

Leetcode Intersection of Two Arrays problem solution


Problem solution in Python.

from collections import Counter
class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        d1, d2 = Counter(nums1), Counter(nums2)
        out = []
        for i in d1.keys():
            if i in d2.keys():
                out.append(i)
        return out



Problem solution in Java.

public int[] intersection(int[] nums1, int[] nums2) {
        HashSet<Integer> set = new HashSet<>();
        ArrayList<Integer> intersection = new ArrayList<>();
        
        for (int i = 0; i < nums1.length; i++) {
            set.add(nums1[i]);
        }
        
        for (int i = 0; i < nums2.length; i++) {
            if (set.remove(nums2[i])) {
                intersection.add(nums2[i]);
            }
        }
        
        int[] result = new int[intersection.size()];
        for (int i = 0; i < intersection.size(); i++) {
            result[i] = intersection.get(i);
        }
        
        return result;
    }


Problem solution in C++.

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        int i = 0 , j = 0 , prev = -1;
        sort(nums1.begin() , nums1.end());
        sort(nums2.begin() , nums2.end());
        vector<int>ans;
        while(i<nums1.size() && j<nums2.size()){
            if(nums1[i] == nums2[j]){
                if(prev == -1 || prev != nums1[i]){
                    ans.push_back(nums1[i]);
                    prev = nums1[i];
                }
                i++;
                j++;
            }
            else if(nums1[i] > nums2[j]){
                j++;
            }
            else if(nums1[i] < nums2[j]){
                i++;
            }
        }
        return ans;
    }
};


Problem solution in C.

int* intersection(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize){
    
    int i, j = 0;
    int size = nums1Size < nums2Size ? nums1Size : nums2Size;
    int hash [1000] = {0};
    int *res = (int *) malloc(size*sizeof(int));
    
    for (i = 0; i < nums1Size; i++)
        hash[nums1[i]] = 1;

    for (i = 0; i< nums2Size; i++) {
        if (hash[nums2[i]] == 1) {
            res[j++] = nums2[i];
            hash[nums2[i]] = 2;
        }
    }
    
    *returnSize = j;
    
    return res;
}