-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path5_union.cpp
132 lines (113 loc) · 2.32 KB
/
5_union.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include <iostream>
#include <algorithm>
using namespace std;
/*
Problem statement: Given two sorted arrays, print union
op should also be sorted, should not contain any duplicate elements
ip: a[] = {3, 5, 8}
b[] = {2, 8, 9, 10, 15}
op: 2 3 5 8 9 10 15
ip: a[] = {2, 3, 3, 3, 4, 4}
b[] = {4, 4}
op: 2 3 4
Naive: Create an auxilary array 'c'
Copy elements of a and b in arr c
now sort arr c
while printing arr c, don't print duplicate elements
Time: O((m+n)*log(m+n))
space: θ(m+n)
*/
void naive_union(int a[], int m, int b[], int n)
{
int c[m + n], i, j;
for (i = 0; i < m; i++)
c[i] = a[i];
for (j = 0; j < n; j++)
c[m + j] = b[j];
sort(c, c + m + n);
for (int k = 0; k < m + n; k++)
if(k==0 || c[k] != c[k-1])
cout << c[i] << " ";
}
/*
Efficient : -We traverse simultaneously through both the arrays
- three cases
a[i]<b[j] : print a[i], move to i + 1
a[i]> b[j] : print b[j] move to j + 1
a[i] == b[j] : print any a[i] or b[j], move to i + 1 & j + 1
- handling duplicates :
if (i>0 && a[i] == a[i - 1])
i++;
continue;
if (j>0 && b[j] == b[j - 1])
j++;
continue;
- process remanining elements of other arrays
Time : O(n+m)
Space: O(1)
*/
void eff_union(int a[], int m, int b[], int n)
{
int i = 0, j = 0;
while(i<m && j<n)
{
if(i>0 && a[i] == a[i-1])
{
++i;
continue;
}
if(j>0 && b[j]==b[j-1])
{
++j;
continue;
}
if(a[i] < b[j])
{
cout << a[i] << " ";
++i;
}
else if(a[i] > b[j])
{
cout << b[j] << " ";
++j;
}
else
{
cout << a[i] << " ";
++i;
++j;
}
}
while(i<m)
if(i>0 && a[i] != a[i-1])
{
cout << a[i] << " ";
++i;
}
while(j<n)
if(j>0 && b[j] != b[j-1])
{
cout << b[j] << " ";
++j;
}
}
int main()
{
int m, n;
cin >> m >> n;
int a[m], b[n];
for (int i = 0; i < m; i++)
cin >> a[i];
for (int i = 0; i < n; i++)
cin >> b[i];
eff_union(a, m, b, n);
return 0;
}
/*
ip:
3 5
3 5 8
2 8 9 10 15
op:
2 3 5 8 9 10 15
*/