题目:
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解法遍历方法相同,唯一需要改变的是在每一次Xi+Xj时,都比较三数和与target的误差,如果误差减小,则更新误差与返回值ret。
不再赘述,直接上代码
import java.util.Arrays;
public class No16_ThreeSumClosest {
public static void main(String[] args){
System.out.println(threeSumClosest(new int[]{0,1,2}, 0));
}
public static int threeSumClosest(int[] num, int target){
if(num.length < 3) return 0;
Arrays.sort(num);
int ret = num[0] + num[1] + num[num.length-1];
int err = ret - target;
if(err < 0) err *= -1;
int k_pre = num[num.length-1]+1;
for(int k=0;k<num.length-2;k++){
if(num[k] == k_pre) continue;
k_pre = num[k];
int i = k+1;
int j = num.length-1;
while(i<j){
if(num[i]+num[j] < target-num[k]){
if(err > target-num[k]-num[i]-num[j]){
err = target-num[k]-num[i]-num[j];
ret = num[k]+num[i]+num[j];
}
i++;
continue;
}
if(num[i]+num[j] > target-num[k]){
if(err > num[i]+num[j]+num[k]-target){
err = num[i]+num[j]+num[k]-target;
ret = num[k]+num[i]+num[j];
}
j--;
continue;
}
return target;
}
}
return ret;
}
}