# C#LeetCode刷题之#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.

Given array nums = [-1, 2, 1, -4], and target = 1.

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

## 示例

```public class Program {

public static void Main(string[] args) {
var intervals = new int[] { -1, 2, 1, -4 };
var target = 1;

var res = ThreeSumClosest(intervals, target);
Console.WriteLine(res);

}

public static int ThreeSumClosest(int[] nums, int target) {
//基础思路同“3数之和”
Array.Sort(nums);
//定义结果、3数之和
var res = 0;
var sum = 0;
//定义上一次和这一次的差
var prediff = int.MaxValue;
var diff = 0;
//定义左右双指针
var j = 0;
var k = 0;
//双指针 j、k 循环分析
for(var i = 0; i < nums.Length - 2; i++) {
j = i + 1;
k = nums.Length - 1;
//左指针不能大于或等于右指针
while(j < k) {
sum = nums[i] + nums[j] + nums[k];
//3数之和与目标值比
//根据结果移动左右指针或相等时直接返回结果
if(sum > target) k--;
else if(sum < target) j++;
else return sum;
//计算差值
diff = Math.Abs(sum - target);
//如果本次更小，重置结果和“上一次差值”
if(diff < prediff) {
res = sum;
prediff = diff;
}
}
}
//返回结果
return res;
}

}
```

```2
```

(2)