3Sum Closest
- 1 min read
- Array
- Sorting
- LC-Medium
- Two Pointers
Approach: Sort + 2Sum
Same as 3Sum but instead of incrementing/decrementing the left/right pointers when the sum == target, we just return the sum.
Implementation
def threeSumClosest(nums: List[int], target: int) -> int:
nums.sort()
ans = math.inf
for i in range(len(nums)):
if i > 1 and nums[i] == nums[i - 1]: continue
l, r = i + 1, len(nums) - 1
while l < r:
sum_ = nums[i] + nums[l] + nums[r]
if sum_ == target: return sum_
if abs(sum_ - target) < abs(ans - target): ans = sum_
elif sum_ < target:
l += 1
while l < r and nums[l] == nums[l - 1]: l += 1
else:
r -= 1
while r > l and nums[r] == nums[r + 1]: r -= 1
return ans