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).
Submissions
与上一题解题思路类似,先将数组nums从小到大排序,然后固定数组中的一个数,去遍历确定另外两个数。不同之处在于定义了两个变量res_min和sum_min,sum_min存储与target最接近时的三个数之和,res_min存储三数之和与target差值的最小值,初始值都为0。当固定数组中一个数是,l 代表它的下一个数,r 代表数组最右端的数。依次遍历求三数之和sum,如果sum等于target则直接返回target,如果小于target则 l 向右移,如果大于target则 r 向左移。当sum与target最接近时,将差值赋值给res_min,sum赋值给sum_min。最终结果返回sum_min。
实现代码如下:
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums = sorted(nums)
res_min,sum_min = 0,0
for i in range(len(nums)):
l =i+1
r = len(nums)-1
while l<r:
sum = nums[i] + nums[l] + nums[r]
res_value = target - sum
if res_min==0 or abs(res_value) <res_min:
res_min = abs(res_value)
sum_min = sum
if sum==target:
return target
elif sum<target:
l+=1
else:
r-=1
return sum_min