三树之和

class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
n=len(nums)
nums.sort()
a=nums[0]+nums[1]+nums[2]
b=nums[n-1]+nums[n-2]+nums[n-3]
if n==3:
return sum(nums)
for i in range(n):
if i>0 and nums[i]nums[i-1]:
i+=1
continue
l=i+1
r=n-1
while l threeSum=nums[i]+nums[l]+nums[r]
ere=threeSum-target
if ere
0:
return threeSum
elif ere<0:
if threeSum>=a:
a=threeSum
l+=1
else:
if threeSum<=b:
b=threeSum
r-=1
if(target-a)>(b-target):
return b
else:
return a

你可能感兴趣的:(三树之和)