Description
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.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
Submission
This approach firstly fixes one of the 3 numbers and then applies the 2-pointer approach.
class Solution: def threeSumClosest(self, nums: List[int], target: int) -> int: res = 0 diff = 9999999999 comb = [] nums.sort() length = len(nums) for i in range(length-2): if i > 0 and nums[i - 1] == nums[i]: continue l = i + 1 r = length - 1 while l < r: s = nums[i] + nums[l] + nums[r] new_diff = s - target if abs(new_diff) < abs(diff): diff = new_diff res = s if new_diff > 0: r -= 1 else: l += 1 return res