Intersection of Two Arrays

Description

Given two arrays, write a function to compute their intersection.

Example 1:

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

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]

Note:

  • Each element in the result must be unique.

  • The result can be in any order.

Solutions

class Solution {
public:
    vector<int> intersection(vector<int> &nums1, vector<int> &nums2) {
        unordered_map<int, int> hash;
        for (int i : nums1)
            hash[i] = 1;
        vector<int> res;
        for (int i : nums2) {
            if (hash.count(i) && hash[i]) {
                res.push_back(i);
                hash[i] = 0;
            }
        }
        return res;
    }
};

class Solution {
public:
    vector<int> intersection(vector<int> &nums1, vector<int> &nums2) {
        unordered_set<int> s(nums1.begin(), nums1.end());
        vector<int> res;
        for (int i : nums2)
            if (s.erase(i))
                res.push_back(i);
        return res;
    }
};

class Solution {
public:
    vector<int> intersection(vector<int> &nums1, vector<int> &nums2) {
        sort(nums1.begin(), nums1.end());
        sort(nums2.begin(), nums2.end());
        vector<int> res;
        for (int i = 0, j = 0; i < nums1.size() && j < nums2.size();) {
            if (nums1[i] < nums2[j])
                ++i;
            else if (nums1[i] > nums2[j])
                ++j;
            else {
                int val = nums1[i];
                res.push_back(val);
                while (i < nums1.size() && nums1[i] == val)
                    ++i;
                while (j < nums2.size() && nums2[j] == val)
                    ++j;
            }
        }
        return res;
    }
};

Last updated