两个列表之间的最小差值对

时间:2019-12-20 07:53:02

标签: python-3.x

我有两个list个整数。我需要从每个列表中找到一个元素,其绝对差异很小。

执行时间为1秒,我的代码超过了允许的时间。如何优化它?

m = int(input())   #number of elements in list1
list1 = list(map(int, input().split()))
z = int(input())    #number of elements in list2
list2 = list(map(int, input().split()))
minDiference = abs(list1[0] - list2[0])
for i in range (m):
    for j in range(z):
        diference = abs(list1[i] - list2[j])
        if difference < mindifference:
            mindifference = difference
print(mindifference)

2 个答案:

答案 0 :(得分:0)

您当前的复杂度为O(m*z),可以通过对列表进行排序将其降低为O(max(m*log(m), z*log(z))

l1 = sorted(list1)
l2 = sorted(list2)

i = j = 0

minimum = float('inf')

while i < m and j < z:
    diff = l1[i] - l2[j]
    minimum = min(minimum, abs(diff))
    if diff < 0: # Means the value of the current position is lower than the l2's, move the l1's pointer
        i += 1
    elif diff > 0: # Quite similar
        j += 1
    else:
        break

print(minimum)

答案 1 :(得分:0)

如果您可以使用numpyitertools,则可以这样做:

import numpy as np
import itertools

x=list(itertools.product(list1,list2))
y=x[np.array(list(map(lambda s: abs(sum(s)), x))).argmin()]
print(y)