```
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int closest = nums[0] + nums[1] + nums[2];
for (int i = 0; i < nums.length; i++) {
int a = nums[i];
int p = i + 1;
int q = nums.length - 1;
while (p < q) {
int b = nums[p];
int c = nums[q];
int sum = a + b + c;
int diff = Math.abs(sum - target);
if (diff < Math.abs(closest - target))// update min
closest = sum;
if (sum == target)
return sum;
if (sum < target)
p++;
else
q--;
}
}
return closest;
}
```