题目描述
给定一个包括 n 个整数的数组 nums
和 一个目标值 target
。找出 nums
中的三个整数,使得它们的和与 target
最接近。返回这三个数的和。假定每组输入只存在唯一答案。
例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.
与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).
题解
通过双指针减少一层循环。比较当前三数和与 target,控制 low 和 high 往差值更小的方向移动。
public int ThreeSumClosest(int[] nums, int target)
{
nums = nums.OrderBy(n => n).ToArray();
var sum = nums[0] + nums[1] + nums[2];
for (var i = 0; i < nums.Length - 2; i++)
{
int low = i + 1, high = nums.Length - 1;
while (low < high)
{
var newSum = nums[i] + nums[low] + nums[high];
var diffNew = target > newSum ? target - newSum : newSum - target;
var diffOld = target > sum ? target - sum : sum - target;
if (diffNew < diffOld)
{
if (newSum == target) return newSum;
sum = newSum;
while (low < high && nums[low] == nums[low + 1]) low++;
while (low < high && nums[high] == nums[high - 1]) high--;
}
if (newSum < target) low++;
else high--;
}
}
return sum;
}