阅读Finding three elements in an array whose sum is closest to a given number后,这是我尝试在执行这样的算法找到三个整数,其总和最接近给定数量N
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
看来,当我想要它返回“cloest”元素时,它总是返回[320,320,259]。我一直在看代码几个小时,但仍然无法弄清楚什么是错的。
嗯我不太确定我得到你的建议。在参数中,目标是我希望尽可能接近的最终总和 – user3277633 2014-09-21 19:53:54
啊,我明白了,谢谢! – user3277633 2014-09-21 20:01:22
太棒了,尽情享受吧! – 2014-09-21 20:03:06