# 算法题丨3Sum Closest

### 描述

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target.
Return the sum of the three integers. You may assume that each input would have exactly one solution.

### 示例

Given array S = {-1 2 1 -4}, and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).


### 算法分析

1. 如果这3个元素之和比目标值大，则需要夹逼结束元素值变小，才有可能接近目标值，所以夹逼结束元素递减；
2. 如果这3个元素之和不比目标值大，则需要夹逼开始元素值变大，才有可能接近目标值，所以夹逼开始元素递增；

### 代码示例(C#)

public int ThreeSumClosest(int[] nums, int target)
{
int res = nums[0] + nums[1] + nums[nums.Length - 1];

//排序后遍历
Array.Sort(nums);
for (int i = 0; i < nums.Length - 2; i++)
{
//从当前后面的元素和最后一个元素，两边夹逼
int lo = i + 1, hi = nums.Length - 1;
while (lo < hi)
{
int sum = nums[i] + nums[lo] + nums[hi];
if (sum > target)
{
hi--;
}
else
{
lo++;
}
//如果此次遍历的3个元素的和更接近，则赋值返回的结果
if (Math.Abs(sum - target) < Math.Abs(res - target))
{
res = sum;
}
}
}
return res;
}


• 时间复杂度O (n²).
• 空间复杂度O (1).

### 附录

posted @ 2018-04-08 10:30  Lancel0t  阅读(...)  评论(...编辑  收藏