和15题非常类似
解法和上一题一样
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int sub = Integer.MAX_VALUE;
int sum = 0;
for(int i=0; i<nums.length-2; i++){
int l=i+1, h=nums.length-1;
while(l < h){
if(Math.abs(nums[l] + nums[h] + nums[i] - target)<sub){
sum = nums[l] + nums[h] + nums[i];
sub = Math.abs(sum - target);
}else if(nums[l] + nums[h] + nums[i] > target){
h--;
}else{
l++;
}
}
}
return sum;
}
}