有一组数,从中取出三个数等于定值,输出这个三个数的所有情况,要求效率尽可能高。
算法如下:
语言:python
a = [1, 2, 4, 5, 6, 3, 7, 8, 9, 10]
r = 15
a.sort()
print(a)
print('a.len =', len(a))
for i in range(0, len(a)):
t = r - a[i]
l = i + 1
h = len(a)-1
while(l < h):
if a[l]+a[h] < t or i == l:
l = l + 1
elif a[l]+a[h] > t or i == h:
h = h - 1
else :
print((a[i], a[l], a[h]))
l = l +1
算法如下:
语言:python
a = [1, 2, 4, 5, 6, 3, 7, 8, 9, 10]
r = 15
a.sort()
print(a)
print('a.len =', len(a))
for i in range(0, len(a)):
t = r - a[i]
l = i + 1
h = len(a)-1
while(l < h):
if a[l]+a[h] < t or i == l:
l = l + 1
elif a[l]+a[h] > t or i == h:
h = h - 1
else :
print((a[i], a[l], a[h]))
l = l +1