> For the complete documentation index, see [llms.txt](https://jimmylin1991.gitbook.io/practice-of-algorithm-problems/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jimmylin1991.gitbook.io/practice-of-algorithm-problems/array/16.-3sum-closest.md).

# 16. 3Sum Closest

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).
```

```cpp
int threeSumClosest(vector<int>& nums, int target) { // time: O(n^2); space: O(1)
    sort(nums.begin(), nums.end());
    int n = nums.size(), res = nums[0] + nums[1] + nums[2];
    for (int i = 0; i < n - 2; ++i) {
        int l = i + 1, r = n - 1;
        while (l < r) {
            int cur = nums[i] + nums[l] + nums[r];
            if (abs(cur - target) < abs(res - target)) res = cur;
            if (cur == target) return res;
            else if (cur < target) {
                ++l;
            } else {
                --r;
            }
        }
    }
    return res;
}
```
