首先排序
随后进行三个数相加
sum<target L++
sum>target R–
class Solution {
public int threeSumClosest(int[] nums, int target) {
int ans=nums[1]+nums[2]+nums[0];
Arrays.sort(nums);
for(int i=0;i<nums.length;i++)
{
int L=i+1,R=nums.length-1;
while(L<R)
{
int sum=nums[i]+nums[L]+nums[R];
ans=Math.abs(target-sum)<Math.abs(target-ans)?sum:ans;
if(sum==target)
return sum;
if(sum<target) L++;
if(sum>target) R--;
}
}
return ans;
}
}