Intersection of Two Arrays in C++

C++Server Side ProgrammingProgramming

Suppose we have two arrays; we have to find their intersections.

So, if the input is like [1,5,3,6,9],[2,8,9,6,7], then the output will be [9,6]

To solve this, we will follow these steps −

  • Define two maps mp1, mp2

  • Define an array res

  • for x in nums1

    • (increase mp1[x] by 1)

  • for x in nums2

    • (increase mp2[x] by 1)

  • for each key-value pair x in mp1

    • cnt := 0

    • cnt := minimum of value of x and mp2[key of x]

    • if cnt > 0, then −

      • insert key of x at the end of res

  • return res

Example 

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
public:
   vector<int> intersection(vector<int>& nums1, vector<int>& nums2){
      unordered_map<int, int> mp1, mp2;
      vector<int> res;
      for (auto x : nums1)
         mp1[x]++;
      for (auto x : nums2)
         mp2[x]++;
      for (auto x : mp1) {
         int cnt = 0;
         cnt = min(x.second, mp2[x.first]);
         if (cnt > 0)
            res.push_back(x.first);
         }
         return res;
      }
};
main(){
   Solution ob;
   vector<int> v = {1,5,3,6,9}, v1 = {2,8,9,6,7};
   print_vector(ob.intersection(v, v1));
}

Input

{1,5,3,6,9},{2,8,9,6,7}

Output

[9, 6, ]
raja
Published on 10-Jun-2020 16:03:35
Advertisements