- Title Requirements:
-
Thinking:
- Sort the array, traverse the array, use double pointer to find all the elements after the current element, the current element and the two elements closest to the target value target, and return the sum of three numbers as res
- Core code:
#Sort the array
nums.sort()
#The result is initialized to the sum of the first three elements of the array
res = nums[0] + nums[1] + nums[2]
#Traversing arrays
for i in range(len(nums)-2):
left = i + 1
right = len(nums) - 1
while left < right:
tmp = nums[i] + nums[left] + nums[right]
#If the sum of the current three elements is closer to the target value, assign the sum of the current three elements to the result res
if abs(tmp - target) < abs(res - target):
res = tmp
if tmp < target:
left += 1
else:
right -= 1
return res
- Full code:
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
if len(nums) < 3:
return 0
nums.sort()
res = nums[0] + nums[1] + nums[2]
for i in range(len(nums)-2):
left = i + 1
right = len(nums) - 1
while left < right:
tmp = nums[i] + nums[left] + nums[right]
if abs(tmp - target) < abs(res - target):
res = tmp
if tmp < target:
left += 1
else:
right -= 1
return res