4. 16_最接近的三数之和
/*
输入:nums = [-1,2,1,-4], target = 1
输出:2
解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
*/
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int ret = nums[0] + nums[1] + nums[2];
for(int i=0; i < nums.length - 2; ++i){
int l = i+1, r = nums.length - 1;
while(l < r){
int sum = nums[i] + nums[l] + nums[r];
if(Math.abs(sum - target) < Math.abs(ret - target)){
ret = sum;
}
if(sum > target) r--;
else if(sum < target) l++;
else return target;
}
}
return ret;
}
}