> For the complete documentation index, see [llms.txt](https://longxingtan.gitbook.io/mle-interview/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://longxingtan.gitbook.io/mle-interview/01_leetcode/01_two_pointers/16.-3sum-closest.md).

# 16. 3Sum Closest

<https://leetcode.com/problems/3sum-closest/>

## solution

```python
class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        nums.sort()
        cloest_sum = float('inf')
        cloest_dis = float('inf')

        for i in range(len(nums) - 2):
            l = i + 1
            r = len(nums) - 1

            while l < r:
                total_sum = nums[i] + nums[l] + nums[r]
                if abs(total_sum - target) < cloest_dis:
                    cloest_dis = abs(total_sum - target)
                    cloest_sum = total_sum

                if total_sum == target:
                    l += 1
                    r -= 1
                elif total_sum > target:
                    r -= 1
                else:
                    l += 1
        return cloest_sum
```

时间复杂度：O(n^2)\
空间复杂度：O()

## follow up

[259. 3Sum Smaller](https://leetcode.com/problems/3sum-smaller/)
