題目
給出一個數組和一個目標值,找出三個數,使得其和和目標值最接近。假設數組中只有一個結果滿足該條件。
Python題解
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
result = nums[0] + nums[1] + nums[2]
for i in range(len(nums) - 2):
low, high = i + 1, len(nums) - 1
while low < high:
sum_tmp = nums[i] + nums[low] + nums[high]
if sum_tmp == target:
return sum_tmp
if abs(result - target) > abs(sum_tmp - target):
result = sum_tmp
if sum_tmp < target:
low += 1
else:
high -= 1
return result