```
public int threeSumClosest(int[] nums, int target) {
if(nums.length==3) return nums[0]+nums[1]+nums[2];
Arrays.sort(nums);
int sum=0;
int maxSum =nums[0]+nums[1]+nums[2];
int idx =0,first=0,last=0;
for(;idx<=nums.length-3;idx++){
first =idx+1;
last =nums.length-1;
while(first<last){
sum = nums[idx]+nums[first]+nums[last];
maxSum = Math.abs(target-maxSum) >Math.abs(sum -target) ? sum: maxSum;
if(sum >target)
last--;
else if(sum<target)
first++;
else return 0;
}
}
return maxSum;
}
```