题目
给出一个数组和一个目标值,找出三个数,使得其和和目标值最接近。假设数组中只有一个结果满足该条件。
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