# 16. 3Sum Closest

{% embed url="<https://leetcode.com/problems/3sum-closest/>" %}

跟Q15相比，就是加一个对差值abs(target-cur)的tracking，遇到差值更小的就更新，差值为0直接返回（不会更小了）。

{% content-ref url="15.-3sum" %}
[15.-3sum](https://xuqiangwen1994.gitbook.io/practice/15.-3sum)
{% endcontent-ref %}

```python
class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        if len(nums) < 3: return []
        nums.sort()
        res = nums[0] + nums[1] + nums[-1]
        for i, n in enumerate(nums[:-2]):
            if i > 0 and n == nums[i-1]: continue
            l, r = i+1, len(nums)-1
            while l < r:
                cur = n + nums[l] + nums[r]
                if abs(target - cur) < abs(target - res): res = cur
                if cur > target: r-=1
                elif cur < target: l+=1
                else:
                    return res
        return res
```
