# 最接近的三数之和

<p>给定一个包括&nbsp;<em>n</em> 个整数的数组&nbsp;<code>nums</code><em>&nbsp;</em>和 一个目标值&nbsp;<code>target</code>。找出&nbsp;<code>nums</code><em>&nbsp;</em>中的三个整数，使得它们的和与&nbsp;<code>target</code>&nbsp;最接近。返回这三个数的和。假定每组输入只存在唯一答案。</p><p>&nbsp;</p><p><strong>示例：</strong></p><pre><strong>输入：</strong>nums = [-1,2,1,-4], target = 1<strong><br />输出：</strong>2<strong><br />解释：</strong>与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。</pre><p>&nbsp;</p><p><strong>提示：</strong></p><ul>	<li><code>3 &lt;= nums.length &lt;= 10^3</code></li>	<li><code>-10^3&nbsp;&lt;= nums[i]&nbsp;&lt;= 10^3</code></li>	<li><code>-10^4&nbsp;&lt;= target&nbsp;&lt;= 10^4</code></li></ul>

以下程序实现了这一功能，请你填补空白处内容：

```cpp
#include <cstdlib>
class Solution
{
public:
	int threeSumClosest(vector<int> &nums, int target)
	{
		sort(nums.begin(), nums.end());
		int cur, left, right;
		cur = 0;
		int closest = nums[0] + nums[1] + nums[2];
		while (cur < nums.size() - 2)
		{
			left = cur + 1;
			right = nums.size() - 1;
			int n;
			while (left < right)
			{
				n = nums[cur] + nums[left] + nums[right];
				if (abs(target - n) < abs(target - closest))
				{
					closest = n;
				}
				if (n == target)
				{
					break;
				}
				____________________________;
				else
				{
					int t = left + 1;
					while (t < right && nums[t] == nums[left])
						t++;
					left = t;
				}
			}
			int t = cur + 1;
			while (t < nums.size() && nums[t] == nums[cur])
				t++;
			cur = t;
		}
		return closest;
	}
};
```

## template

```cpp
#include <cstdlib>
class Solution
{
public:
	int threeSumClosest(vector<int> &nums, int target)
	{
		sort(nums.begin(), nums.end());
		int cur, left, right;
		cur = 0;
		int closest = nums[0] + nums[1] + nums[2];
		while (cur < nums.size() - 2)
		{
			left = cur + 1;
			right = nums.size() - 1;
			int n;
			while (left < right)
			{
				n = nums[cur] + nums[left] + nums[right];
				if (abs(target - n) < abs(target - closest))
				{
					closest = n;
				}
				if (n == target)
				{
					break;
				}
				else if (n > target)
				{
					int t = right - 1;
					while (t > left && nums[t] == nums[right])
						t--;
					right = t;
				}
				else
				{
					int t = left + 1;
					while (t < right && nums[t] == nums[left])
						t++;
					left = t;
				}
			}
			int t = cur + 1;
			while (t < nums.size() && nums[t] == nums[cur])
				t++;
			cur = t;
		}
		return closest;
	}
};
```

## 答案

```cpp
else if (n > target)
{
	int t = right - 1;
	while (t > left && nums[t] == nums[right])
		t--;
	right = t;
}
```

## 选项

### A

```cpp
else if (left > target)
{
	int t = right + 1;
	while (t > left && nums[t] == nums[right])
		t--;
	right = t;
}
```

### B

```cpp
else if (left > target)
{
	int t = right - 1;
	while (t > left && nums[t] == nums[right])
		t--;
	right = t + 1;
}
```

### C

```cpp
else if (left > target)
{
	int t = right - 1;
	while (t > left && nums[t] == nums[right])
		t--;
	right = t;
}
```