閱讀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