我正在研究这个问题(不是家庭作业) 给定一个未排序的整数列表,A = {a1,a2,...,an)你能找到它们之间具有最小绝对差异的元素对吗?如果有多对,请找到它们。
这就是我提出的:
num = int(input())
array = [int(x) for x in input().split()]
diff = []
for i in range(len(array)):
for j in array:
diff.append(array[i]- j)
total = []
for i in diff:
if i > 0:
total.append(i)
grail = min(total)
holy = []
for i in range(len(array)):
for j in array:
if ((array[i] - j) == grail):
holy.append(array[i])
holy.append(j)
final = sorted(holy)
for item in final:
print(item, end = ' ')
这种情况在少数情况下运行,但在大输入时会出现运行时错误,我可能会尝试任何建议吗?
例如:
Input = [-20 -3916237 -357920 -3620601 7374819 -7330761 30 6246457 -6461594 266854 -520 -470 ]
Output = -520 -470 -20 30
说明=(-470) - (-520)= 30 - ( - 20)= 50,这是最小的差异。
提前致谢
答案 0 :(得分:2)
我没有费心去检查代码的正确性,因为实现的复杂性为O(n ^ 2)
for i in range(len(array)):
for j in array:
if ((array[i] - j) == grail):
holy.append(array[i])
holy.append(j)
所需答案需要具有优选的O(log n)复杂度。为了实现这一目标,您需要预先对列表进行排序。
from unittest import TestCase
import unittest
from sys import maxsize
from itertools import tee
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip(a, b)
def solution(n):
n = sorted(n)
pairs = []
diff = maxsize
for l, u in pairwise(n):
if u - l <= diff:
diff = u - l
pairs.append((diff, (l,u)))
pairs = sorted(pairs)
least = pairs[0][0]
return list(map(lambda x: x[1], filter(lambda x: x[0] == least, pairs)))
class TestLeastDiffrence(TestCase):
def testSimple(self):
n = [-20, -3916237, -357920, -3620601, 7374819, -7330761, 30, 6246457, -6461594, 266854, -520, -470]
self.assertEqual(solution(n),[(-520, -470), (-20, 30)])
if __name__ == '__main__':
unittest.main()