-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathunion_sorted_arrays.rb
92 lines (78 loc) · 1.32 KB
/
union_sorted_arrays.rb
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
# Given two sorted arrays, find their union and intersection.
def union(ar1, ar2)
i = 0
j = 0
l = ar1.length
m = ar2.length
common = []
while i < l && j < m
if ar1[i] == ar2[j]
common << ar1[i]
i += 1
j += 1
elsif ar1[i] > ar2[j]
common << ar2[j]
j += 1
else
common << ar1[i]
i += 1
end
end
while i < l
common << ar1[i]
i += 1
end
while j < m
common << ar2[j]
j += 1
end
common
end
def union_if_duplicates_prsent(ar1, ar2)
i = 0
j = 0
l = ar1.length
m = ar2.length
common = []
while i < l && j < m
if ar1[i] == ar2[j]
common << ar1[i]
i += 1
j += 1
elsif ar1[i] > ar2[j]
common << ar2[j]
j += 1
else
common << ar1[i]
i += 1
end
end
while i < l
common << ar1[i]
i += 1
end
while j < m
common << ar2[j]
j += 1
end
common
end
def intersection(ar1, ar2)
i = 0
j = 0
common = []
while i < ar1.length
if ar1[i] == ar2[j]
common << ar1[i]
i += 1
j += 1
end
j += 1 while ar1[i] > ar2[j] && j < ar2.length - 1
i += 1 while ar2[j] > ar1[i] && i < ar1.length - 1
break if i == ar1.length - 1 || j == ar2.length - 1
end
common
end
arr1 = [1, 2, 4, 5, 6]
arr2 = [2, 3, 5, 7]
puts union(arr1, arr2).to_s