给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.
与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum-closest
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
审题:
求三个数之和最接近给定的值,和15题相似,求结果的绝对值最小的。
思考:
和15题相似,map前两个值存储map,再将target-这两个值的和存为key。最后判断key最小的。
解题:
// 思路115题的三数之和,结果最接近target的,判断的方式是用target减结果,越小越接近。
public int threeSumClosest(int[] num, int target) {
//初始化要输入的值,每次循环结束之前都要对比,将最小的设置到result中。
int result = num[0] + num[1] + num[num.length - 1];
Arrays.sort(num);
for (int i = 0; i < num.length - 2; i++) {
int start = i + 1, end = num.length - 1;
while (start < end) {
int sum = num[i] + num[start] + num[end];
//如果比输入值大,右侧向左移动
if (sum > target) {
end--;
//如果比输入值小,左侧向右移动
} else {
start++;
}
//取绝对值
if (Math.abs(sum - target) < Math.abs(result - target)) {
//将本次循环的最小值存在这里,每次循环的时候都比较,最后返回最小的。
result = sum;
}
}
}
return result;
}
知识点:
与15题不同的是,不需要双向移动,寻找最接近的。