packagecom.ytx.array;
importjava.util.Arrays;
/** 题目: 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).
*
*@authoryuantian xin
* 找到三个数,并且它们的和与target的差为最小,参考3sum的解法,只需记录当前最优解并不断更新其值就可。
*/
publicclassThree_sum_closest {
publicintthreeSumClosest(int[]num,inttarget) {
intlen = num.length;
if(num==null || len < 3) return0;
Arrays.sort(num);
intres_sum = num[0] +num[1] +num[len-1];
intminDiff = res_sum - target;
for(inti= 0; i < len - 2; i++) {
intleft= i + 1;
intright= len - 1;
while(left<right) {
intcur_sum= num[i] +num[left] +num[right];
if(cur_sum<target) {
if(Math.abs(cur_sum-target) < Math.abs(minDiff)) {
res_sum=cur_sum;
minDiff=cur_sum - target;
}
left++;
}elseif(cur_sum>target) {
if(Math.abs(cur_sum-target) < Math.abs(minDiff)) {
res_sum=cur_sum;
minDiff=cur_sum - target;
}
right--;
}else{
returncur_sum;
}
}
}
returnres_sum;
}
publicstaticvoid main(String[]args) {
int[]num= {-1,2,1,-4};
inttarget= 1;
intsum;
sum=new Three_sum_closest().threeSumClosest(num,target);
System.out.println(sum);
}
}