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).
这个和3sum的思路一样
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).
这个和3sum的思路一样
public int threeSumClosest(int[] num, int target) {
int result = 0;
int temp = Integer.MAX_VALUE;
if(num == null || num.length<3){
return 0;
}
Arrays.sort(num);
for(int i = 0 ;i<num.length-1;i++){
int tar = target - num[i];
int end = num.length-1;
int begin = i+1;
while(end > begin){
if(tar> num[end]+num[begin]){
temp = Math.abs(temp)<Math.abs(tar- num[end] - num[begin])?temp:tar- num[end] - num[begin];
begin++;
while(begin<num.length&&num[begin] == num[begin-1]){
begin++;
}
}else if(tar<num[end]+num[begin]){
temp = Math.abs(temp)<Math.abs(tar- num[end] - num[begin])?temp:tar- num[end] - num[begin];
end--;
while(end>-1&&num[end] == num[end+1]){
end--;
}
}else {
return target;
}
}
}
result = target - temp;
return result;
}