题目分析
这个题目与三数之和的题目非常类似,是同一个题目,只要记录最大的差值,然后返回就好了
Java代码
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int span = Integer.MAX_VALUE;
boolean flag = true;
for(int i=0;i<nums.length;i++){
int l = i+1;
int r = nums.length-1;
while(l<r){
if(nums[i] + nums[l] + nums[r] == target){
// 调整l和r,遍历所有i产生的三元组
span = 0;
break;
}else if(nums[i] + nums[l] + nums[r] < target){
int tmp = target - (nums[i] + nums[l] + nums[r]);
if(span>tmp){
span = tmp;
flag = true;
}
l++;
}else{
int tmp = (nums[i] + nums[l] + nums[r]) - target;
if(span>tmp){
span = tmp;
flag = false;
}
r--;
}
}
}
System.out.println("span = " + span);
System.out.println("target = " + target);
return flag ? target-span : target+span;
}