法1:排序+双指针
class Solution {
public int threeSumClosest(int[] nums, int target) {
int n = nums.length;
Arrays.sort(nums);
// int minAbs =10000000;//2147483647
int minAbs = 10000000;
for(int i = 0;i<n;i++){
//保证和上一次枚举的元素不相同
if(i>0&&nums[i]==nums[i-1])
continue;
int l = i+1,r = n-1;
while(l<r){
int result = nums[i] + nums[l] +nums[r];
if(result==target)
return target;
if(Math.abs(result-target)<Math.abs(minAbs-target))
minAbs = result;
if(result>target){
int r1 = r-1;
//跳过重复元素
while(r1>l&&nums[r1]==nums[r]){
r1--;
}
r = r1;
}
if(result<target){
int l1 = l+1;
while(l1<r&&nums[l1]==nums[l]){
l1++;
}
l = l1;
}
}
}
return minAbs;
}
}