这个问题已经在这里有了答案: > Finding three elements in an array whose sum is closest to a given number 13个
在阅读了约Finding three elements in an array whose sum is closest to a given number之后,这是我尝试实现这种算法的尝试
def findThree(seq, goal):
# initialize the differences
goalDifference = float("inf")
dl = -1
dr = -1
dx = -1
for x in range(len(seq)-1):
left = x+1
right = len(seq)-1
while (left < right):
# if the absolute value of the previous set and the goal is less than the current goalDifference,
# keep track of the new set
if(abs(goal - (seq[left] + seq[right] + seq[x])) < goalDifference):
dl = left
dr = right
dx = x
tmp = seq[left] + seq[right] + seq[x]
if tmp > goal:
right -= 1
elif tmp < goal:
left += 1
else:
return [seq[left],seq[right],seq[x]]
# if no match is found, return the closest set
return [seq[dl],seq[dr], seq[dx]]
在给定的条件下,该算法非常适合查找精确解
arr = [89, 120, 140, 179, 199, 259, 259, 259, 320, 320]
findThree(arr, 349) // want to get [120, 140, 89]
>> [120, 140 89] // success
findThree(arr, 439) // want to get [140, 179, 120]
>> [140, 179,120] // success
但是,当我想查看是否返回最接近的值时,它会返回
findThree(arr, 350) // only 1 more than 349, should return [120, 140, 89]
>> [320, 320, 259] // fail
findThree(arr, 440) // only 1 more than 439, should return [140, 179, 120]
>> [320, 320, 259] // fail
看来,当我希望它返回“最接近的”元素时,它总是返回[320、320、259].我已经看了几个小时的代码,但仍然无法找出问题所在.
解决方法:
我迅速查看了您的代码,主要问题是“目标差异”从未改变.
您需要随手挤压“目标差异”,否则所有组合都在“目标差异”之内,显然您最终将得到最后一组作为答案.