Array Intersection
You have been given two integer arrays/list(ARR1 and ARR2) of size N and M, respectively. You need to print their intersection; An intersection for this problem can be defined when both the arrays/lists contain a particular value or to put it in other words, when there is a common value that exists in both the arrays/lists.
Note :
Input format :
Output format :
Constraints :
Sample Input 1 :
Sample Output 1 :
Sample Input 2 :
Sample Output 2 :
Explanation for Sample Output 2 :
Since, both input arrays have two '2's, the intersection of the arrays also have two '2's. The first '2' of first array matches with the first '2' of the second array. Similarly, the second '2' of the first array matches with the second '2' if the second array.
#include <iostream>
#include <algorithm>
using namespace std;
#include "solution.h"
int main()
{
int t;
cin >> t;
while (t--)
{
int size1, size2;
cin >> size1;
int *input1 = new int[size1];
for (int i = 0; i < size1; i++)
{
cin >> input1[i];
}
cin >> size2;
int *input2 = new int[size2];
for (int i = 0; i < size2; i++)
{
cin >> input2[i];
}
intersection(input1, input2, size1, size2);
delete[] input1;
delete[] input2;
cout << endl;
}
return 0;
}
/*
void intersection(int *arr1, int *arr2, int n, int m)
{
//Write your code here
set<int> s(arr1,arr1+n;
vector<int>ans;
for(int x:arr2)
if(s.erase(x))
ans.push_back(x);
return ans;
}
*/
void intersection(int input1[], int input2[], int size1, int size2) {
// sort(input1 ,input1+size1);
// sort(input2 ,input2+size2);
// int i=0,j=0;
// while(i<size1 && j<size2)
// {
// if(input1[i]<input2[j])
// i++;
// else if(input1[i]>input2[j])
// j++;
// else if(input1[i]==input2[j])
// {
// cout<<input1[i]<<" ";
// i++;
// j++;
// }
// }
sort(input1,input1+size1);
sort(input2,input2+size2);
int i=0,j=0;
while(size1>i && size2>j){
if(input1[i]>input2[j]) j++;
else if(input2[j]>input1[i]) i++;
else if(input1[i]==input2[j]){
cout<<input1[i]<<" ";
i++;
j++;
}
}
}
Comments
Post a Comment