##16. 3Sum Closest
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.
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).
思路
- 排序原数列
- 保存左边三个值的和在result中,移动第一个数,第二个数,第三个数的位置,再次求和,存在sum中
- 比较sum - target 和 result - target 的差别,result中保存与target差值小的
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int result = nums[0] + nums[1] + nums[2];
for ( int i= 0; i<nums.length; i++){
int j = i+1;
int k = nums.length -1;
while (j < k){
int sum = nums[i] + nums[j] + nums[k]; //必须在while内
//比较sum, result 跟target之间的差距,result中保存跟target差距小的那个值
if (Math.abs(sum-target) < Math.abs(result-target))
result = sum;
//如果sum比目标值小,左边加,否则,右边减。当sum 等于result的时候,放哪边都行。
if (sum < target)
j++;
else
k--;
}
}
return result;
}