题目描述
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
思路分析
这题和求三个数之和为定值的思路相似。不同之处在与求最接近target的三个数。排序后,我们可以先设定ans = nums[0]+nums[1]+nums[2],然后依次遍历,对于任意组合的三个数值,他们的和sum和target差的绝对值与ans与target差的绝对值相比较,不断更新ans,使得其保持最小值。
代码
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int ans = nums[0]+nums[1]+nums[2];
int len = nums.length;
int sum = 0;
for (int i = 0; i < len-2; i++) {
int j = i+1,k = len-1;
while(j<k)
{
sum = nums[i]+nums[j]+nums[k];
if(Math.abs(sum-target)<Math.abs(ans-target))
{
ans = sum;
}
if(sum>target)
k--;
else
j++;
}
}
return ans;
}