题目描述
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.
样例
Example:
Given array nums = [-1, 2, 1, -4], and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
思路分析
和前面3sum思路一致,不过是判断条件换了一下,相等 变为 差最小,不多赘述了
代码
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int count = nums[0]+nums[1]+nums[nums.length-1];
for (int i = 0; i < nums.length-2; i++) {
int low = i+1;
int high = nums.length-1;
while (low < high){
int sum = nums[i]+nums[low]+nums[high];
if ((Math.abs(count-target) > (Math.abs(sum-target)))){
count = sum;
}
if (sum>target) {
high--;
}
else {
low++;
}
}
}
return count;
}
结果