Array Intersection
Array Intersection
Send Feedback
Array Intersection
Input arrays/lists can contain duplicate elements.
The intersection elements printed would be in ascending order.
The first line contains an Integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow.
The first line of each test case or query contains an integer 'N' representing the size of the first array/list.
The second line contains 'N' single space separated integers representing the elements of the first the array/list.
The third line contains an integer 'M' representing the size of the second array/list.
The fourth line contains 'M' single space separated integers representing the elements of the second array/list.
For each test case, print the intersection elements in a row, separated by a single space.
Output for every test case will be printed in a separate line.
1 <= t <= 10^2
0 <= N <= 10^6
0 <= M <= 10^6
Time Limit: 1 sec
2
6
2 6 8 5 4 3
4
2 3 4 7
2
10 10
1
10
2 3 4
10
1
4
2 6 1 2
5
1 2 3 4 2
1 2 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.
/*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++; } } }
#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;}
Comments
Post a Comment