-
Notifications
You must be signed in to change notification settings - Fork 0
/
16.py
21 lines (21 loc) · 857 Bytes
/
16.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
def threeSumClosest(nums,target):
nums=sorted(nums)
closest_num=nums[0]+nums[1]+nums[2]
closest=abs(target-(nums[0]+nums[1]+nums[2]))
for j in range(len(nums)-2):
l=j+1
r=len(nums)-1
while l<r:
if (nums[l]+nums[r]+nums[j])<target:
if abs(target-(nums[l]+nums[r]+nums[j]))<closest:
closest=abs(target-(nums[l]+nums[r]+nums[j]))
closest_num=nums[l]+nums[r]+nums[j]
l+=1
elif (nums[l]+nums[r]+nums[j])>target:
if abs(target-(nums[l]+nums[r]+nums[j]))<closest:
closest=abs(target-(nums[l]+nums[r]+nums[j]))
closest_num=nums[l]+nums[r]+nums[j]
r-=1
else:
return target
return closest_num