16.最接近的三数之和
class Solution {
public int threeSumClosest(int[] nums, int target) {
int n=nums.length;
Arrays.sort(nums);
int best=10000000;
for(int first=0;first<n-2;first++){
if(first>0&&nums[first]==nums[first-1]){
continue;
}
int second=first+1;
int third=n-1;
while(second<third){
int sum=nums[first]+nums[second]+nums[third];
if(sum==target){
return target;
}
if(Math.abs(sum-target)<Math.abs(best-target)){
best=sum;
}
int temp;
if(sum>target){
temp=third;
while(second<temp&&nums[temp]==nums[third]){
temp--;
}
third=temp;
}else{
temp=second;
while(temp<third&&nums[temp]==nums[second]){
temp++;
}
second=temp;
}
}
}
return best;
}
}