思路:跟三数之和的思路相同,只不过这里是最接近target的三个数,同样将数组排序,固定第一个数,后面两个数用双指针移动,当三个数的和大于target,那么将右边指针左移,如果三个数的和小于target,那么将左边指针右移。
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
min_value = 1000000
for k in range(len(nums)-2):
i = k+1
j = len(nums)-1
while i < j:
s = nums[k] + nums[i] + nums[j]
if s == target:
return target
elif s < target:
if target-s < min_value:
min_value = target-s
res = s
i += 1
else:
if s-target < min_value:
min_value = s-target
res = s
j -= 1
return res