-
Notifications
You must be signed in to change notification settings - Fork 56
/
union_of_sorted_arrs.cpp
55 lines (48 loc) · 1.16 KB
/
union_of_sorted_arrs.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include<iostream>
#include<vector>
using namespace std;
vector<int> findUnion(int arr1[], int arr2[], int n, int m)
{
vector<int> u;
int i=0, j=0;
while(i<n && j<m){
if(arr1[i]<=arr2[j]){
if(u.size() == 0 || arr1[i]!=u.back()){
u.push_back(arr1[i]);
}
i++;
}
else{
if(u.size() == 0 || arr2[j]!=u.back()){
u.push_back(arr2[j]);
}
j++;
}
}
while(i<n){
if(u.size() == 0 || arr1[i]!=u.back()){
u.push_back(arr1[i]);
}
i++;
}
while(j<m){
if(u.size() == 0 || arr2[j]!=u.back()){
u.push_back(arr2[j]);
}
j++;
}
return u;
}
int main() {
int arr1[] = {2,2,3,4,5};
int arr2[] = {1,1,2,3,4};
int size1 = sizeof(arr1)/sizeof(arr1[0]);
int size2 = sizeof(arr2)/sizeof(arr2[0]);
vector<int> ans = findUnion(arr1, arr2, size1, size2);
cout<<"\nUnion of both arrays: \n";
for(int i: ans){
cout<<i<<" ";
}
cout<<endl;
return 0;
}