要求3个数的和与目标最接近 ,可以转换为求2个数+1固定值的和与目标最接近
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
res = nums[0] + nums[1] + nums[2]
l = len(nums)
for i in range(l):
start = i + 1
end = l - 1
while start < end:
tmp = nums[i] + nums[start] + nums[end]
if abs(target - tmp) < abs(target - res):
res = tmp
if tmp > target:
end -= 1
elif tmp < target:
start += 1
else:
return res
return res
注意的点:
1. if...elif...else是缩紧同样的距离
2.排完序之后,若和>target, end--,若和<target,则start++