题目描述
给定一个包括 n 个整数的数组 S,找出 S 中的三个整数使得他们的和与给定的数 target 最接近。返回这三个数的和。假定每组输入只存在一个答案。
例如,给定数组 S = {-1 2 1 -4}, 并且 target = 1.
与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).
解:
采用和十五题类似的思想,将判断改为三个数加起来大于target时,大的一头向小的方向移动。反之,小的一段向大的方向移动。
java代码:
class Solution {
public int threeSumClosest(int[] nums, int target) {
int res = nums[0] + nums[1] + nums[nums.length - 1];
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++){
int start = i + 1;
int end = nums.length - 1;
while (start < end){
int sum = nums[i] + nums[start] + nums[end];
if (sum < target) start++;
else end--;
if(Math.abs(sum - target) < Math.abs(res - target)) res = sum;
}
}
return res;
}
}