Sunday, March 14, 2021

Intersection of Two Arrays

 349. Intersection of Two Arrays

Easy

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.

 

========= 2 sets approach =======

class Solution {

public:

    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {

        vector<int> ans;

        if (nums1.size() == 0 || nums2.size() == 0) {

            return ans;

        }

        unordered_set<int> st_a(nums1.begin(), nums1.end());

        unordered_set<int> sol;

        for (auto num : nums2) {

            if (st_a.count(num) != 0) {

                sol.insert(num);

            }

        }

        ans = vector<int>(sol.begin(), sol.end());

        return ans;

    }

};


============ Single set approach =======
// Author: Huahua
// Running time: 7 ms
class Solution {
public:
  vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
    unordered_set<int> m(nums1.begin(), nums1.end());
    vector<int> ans;
    for (int num : nums2) {
      if (!m.count(num)) continue;
      ans.push_back(num);
      m.erase(num);
    }
    return ans;
  }
};

No comments:

Post a Comment