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).
LeetCode:链接
这道题目给了我们一个nums array 和一个 target, 让我们找到一组三数之和,并且是最接近于target的。由于我们做过了三数之和,所以差不多是一样方法来做这道题(这里充分说明了,要老老实实顺着题号做下去,较先的题目都可以被用来辅助之后的题)。方法就是先sort一下array,为啥要sort呢,因为要用到two pointers 来遍历找两数之和,只有在从小到大排序之后的结果上,才能根据情况移动left 和right。 当确定好了第一个数字后,就在剩下的array里找两数之和,在加上第一个数字,用这个temp_sum减去target 来得到temp_diff,如果temp_diff比之前的小,那么更新diff 和 closestSum。 利用two pointers 特性, 如果temp_sum 比target 小的话,说明我们需要更大的sum,所以要让left++以便得到更大的sum。 如果temp_sum 比target 大的话,我们就需要更小的sum。如果相等的话,直接return 就可以了。因为都相等了,那么差值就等于0,不会有差值再小的了。
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
if len(nums) < 3:
return []
# 有序
nums.sort()
# 选数组中的数或正无穷 float('Inf')
ans = sum(nums[:3])
for idx in range(len(nums)-2):
start = idx + 1
end = len(nums) - 1
while start < end:
# 绝对值距离不断更新
if abs(nums[idx] + nums[start] + nums[end] - target) < abs(ans - target):
ans = nums[idx] + nums[start] + nums[end]
if nums[idx] + nums[start] + nums[end] == target:
return target
elif nums[idx] + nums[start] + nums[end] < target:
start += 1
else:
end -= 1
return ans