题目描述
解题方法
def threeSumClosest(self, nums: List[int], target: int) -> int:
if len(nums)<3:
return None
nums.sort()
best = 1e7
for i in range(len(nums)):
if i>0 and nums[i]==nums[i-1]:
continue
p = i+1
q = len(nums)-1
while p<q:
sum = nums[i]+nums[p]+nums[q]
if sum == target:
return target
c = abs(target-sum)
if c < abs(target-best):
best = sum
if sum<target:
p += 1
while p<q and nums[p] == nums[p-1]:
p = p + 1
if sum>target:
q -= 1
while p<q and nums[q] == nums[q+1]:
q = q -1
return best