define two indexs starting from 0 for the arrays. Compare values the two indexs referring to, and move the indexs under each condition.
- The union of two sorted arrays
def union(list1, list2):
l1, l2 = 0, 0
n1, n2 = len(list1), len(list2)
res = []
while True:
if l1 == n1:
res += list2[l2:]
break
if l2 == n2:
res += list1[l1:]
break
if list1[l1] < list2[l2]:
res.append(list1[l1])
l1 += 1
elif list1[l1] > list2[l2]:
res.append(list2[l2])
l2 += 1
else:
res.append(list2[l2])
l2 += 1
l1 += 1
print(res)
- The intersection of two sorted arrays
def intersection(list1, list2):
l1, l2 = 0, 0
n1, n2 = len(list1), len(list2)
res = []
while l1 < n1 and l2 < n2:
if list1[l1] < list2[l2]:
l1 += 1
elif list1[l1] > list2[l2]:
l2 += 1
else:
res.append(list1[l1])
l2 += 1
l1 += 1
print(res)