寻找数组中三个数之和最接近目标值的算法
思路:
题目要求找到三个整数,使它们的和与目标值最接近,因此我们可以先将数组进行排序,然后固定一个数,再用双指针法去寻找另外两个数。
具体来说,我们可以先将数组 nums 排序,然后枚举第一个数 a,将另外两个数的和 b+c 与 target-a 进行比较:
- 若 b+c > target-a,则说明此时三数之和过大,因此我们将指针 right 左移;
- 若 b+c < target-a,则说明此时三数之和过小,因此我们将指针 left 右移;
- 若 b+c = target-a,则说明已经找到了最优解,直接返回 target。
代码:
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
n = len(nums)
best = float('inf')
for i in range(n):
left = i + 1
right = n - 1
while left < right:
total = nums[i] + nums[left] + nums[right]
if abs(total - target) < abs(best - target):
best = total
if total > target:
right -= 1
elif total < target:
left += 1
else:
return target
return best
原文地址: https://www.cveoy.top/t/topic/mkWW 著作权归作者所有。请勿转载和采集!