class Solution {
public static int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int min = 999999999;
int ans = nums[0] + nums[1] + nums[2];
for (int i = 0; i < nums.length - 2; i++) {
int left = i + 1;
int right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
int num = Math.abs(sum - target);
if (num < min) {
ans = sum;
min = num;
}
if (left < right && sum == target) {
return sum;
} else if (left < right && sum > target) {
right--;
} else if (left < right && sum < target) {
left++;
}
}
}
return ans;
}
}