Categories:

Tags:



Problem

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.

Constraints

  • 1 <= nums1.length, nums2.length <= 1000
  • 0 <= nums1[i], nums2[i] <= 1000

Solution

The problem Intersection of Two Arrays can be solved using a hash map twice, first to find unqiue elements from one array and then to find intersection of two arrays.

Implementation

class Solution
{
  private:
    char hashmap[1001];

  public:
    vector<int> intersection(vector<int> &nums1, vector<int> &nums2)
    {
        for (int num : nums1)
            hashmap[num] = 1;

        for (int num : nums2)
            if (hashmap[num] == 1)
                hashmap[num] = 2;

        vector<int> ret;
        for (int i = 0; i <= 1000; i++)
            if (hashmap[i] == 2)
                ret.push_back(i);

        return ret;
    }
};