LeetCode实战:16. 最接近的三数之和
题目
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
示例:
例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.
与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
算法实现
public class Solution {
public int ThreeSumClosest(int[] nums, int target) {
Array.Sort(nums);
int res = nums[0] + nums[1]+ nums[nums.Length-1];
for(int i=0; i<nums.Length-2; i++)
{
int j = i + 1;
int k = nums.Length - 1;
while(j < k)
{
int s = nums[i] + nums[j] + nums[k];
if(Math.Abs(s - target) < Math.Abs(res - target))
{
res = s;
}
if(s < target)
j++;
else if(s > target)
k--;
else
return res;
}
}
return res;
}
}
思路
类似于前一题。首先排序,再用外层控制一个元素的循环,内层用双指针,一个从头到尾扫描,另一个从尾到头扫描,判断三个元素的值之和与目标数值的差。然后再根据大小移动指针。
结果
