3Sum Closest
Two pointer
Problem
Given an array nums
of n integers and an integer target
, find three integers in nums
such that the sum is closest to target
. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Solution
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
targetDiff = float("inf")
for i in range(len(nums)-2):
left = i+1
right = len(nums)-1
while left < right:
currSum = nums[i]+nums[left]+nums[right]
if(currSum == target):
return currSum
#we do abs because the currSum can be greater than target and since
#we need the difference we do abs
elif abs(currSum - target) < abs(targetDiff - target):
targetDiff = currSum
#if we had duplicates, in here is where we would do the while loop
#to check
if(currSum < target):
left+=1
elif(currSum > target):
right-=1
return targetDiff
Last updated
Was this helpful?