先使用归并排序进行排序,再建立其补集,对这两个排序后的集合进行元素比较,找到相同元素即寻找到答案
def findthecomplementary(s, x):
l1 = list(s)
l2 = []
n = len(l1)
mergesort(l1, 0, n-1)
for a in reversed(l1):
if (x - a) != a:
l2.append(x - a)
n2 = len(l2)
i, j = 0, 0
while (i < n) & (j < n2):
if l1[i] < l2[j]:
i += 1
elif l1[i] > l2[j]:
j += 1
else:
print str(l1[i]) + " + " + str(x - l1[i]) + " = " + str(x)
return
print "There is no such pair"
return
s = set([1, 3, 5, 7, 7, 9])
x = 12
findthecomplementary(s, x)