1. 题目

给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。

示例:
输入:nums = [-1,2,1,-4], target = 1
输出:2
解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。

提示:
3 <= nums.length <= 10^3
-10^3 <= nums[i] <= 10^3
-10^4 <= target <= 10^4

2. 题解

import math
from typing import List


class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
res = math.inf
n = len(nums)
nums.sort()
for first in range(n - 2):
if first > 0 and nums[first] == nums[first -1]:
continue
second = first + 1
third = n - 1
while second < third:
s = nums[first] + nums[second] + nums[third]
if abs(s - target) < abs(res - target):
res = s
if s > target:
third -= 1
elif s < target:
second += 1
else:
return target
return res


if __name__ == "__main__":
s = Solution()
nums = [0,0,0]
print(s.threeSum(nums, 1))