-
Medium
-
Given an integer array
nums
of lengthn
and an integertarget
, find three integers innums
such that the sum is closest totarget
.Return the sum of the three integers.
You may assume that each input would have exactly one solution.
This problem has a similar build up like problem 15.-3sum.md. But here we might not find the set of numbers that adds up to be the target, therefore we keep an record of the minimal difference each time we try.
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
n=len(nums)
answer=[]
mini=float('inf')
for i in range(n):
temp=target-nums[i]
l=i+1
r=n-1
while l<r:
currsum=nums[l]+nums[r]-temp
if abs(mini)>abs(currsum):
mini=currsum
if currsum==0:
return target;
elif currsum<0:
l+=1
else:
r-=1
return target+mini