// 跟之前15题3Sum类似,也是双指针,只不过这里是取最小的差值
// 还是先sort一遍,从小到大开始,left表示第二个数,right表
// 示第三个数,将三数之和与target差值作为优化目标,取最小值
// 即得到答案
class Solution {
public int threeSumClosest(int[] nums, int target){
Arrays.sort(nums);
int dif = Integer.MAX_VALUE;
int res = Integer.MAX_VALUE;
for(int i = 0;i < nums.length; i++){
int left = i + 1;
int right = nums.length - 1;
while(left < right){
int ans = nums[i] + nums[left] + nums[right] - target;
if (ans == 0){
return target;
}else {
if (ans < 0)
left ++;
else right --;
if (dif > Math.abs(ans)){
dif = Math.abs(ans);
res = ans + target;
}
}
}
}
return res;
}
}