-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUnionOfTwoSortedArrays.cpp
53 lines (50 loc) · 1.17 KB
/
UnionOfTwoSortedArrays.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
//arr1,arr2 : the arrays
// n, m: size of arrays
vector<int> findUnion(int arr1[], int arr2[], int n, int m)
{
vector<int> res;
int i=0,j=0;
while(i<n && j<m){
if(res.empty()==false){ //checking this condition first to avoid
if(arr1[i]==res.back()){ //error in res.back() if res is empty
i++;
continue;
}
if(arr2[j]==res.back()){
j++;
continue;
}
}
if(arr1[i]<arr2[j]){
res.push_back(arr1[i]);
i++;
}
else{
res.push_back(arr2[j]);
j++;
}
}
//checking & filling if there are elements left in the first array
while(i<n){
if(arr1[i]==res.back()){
i++;
continue;
}
else{
res.push_back(arr1[i]);
i++;
}
}
//checking & filling if there are elements left in the right array
while(j<m){
if(arr2[j]==res.back()){
j++;
continue;
}
else{
res.push_back(arr2[j]);
j++;
}
}
return res;
}