class Solution {
public int threeSumClosest(int[] nums, int target) {
// corner cases
if (nums.length == 1) {
return nums[0];
}
if (nums.length == 2) {
int diff1 = Math.abs(nums[0] - target);
int diff2 = Math.abs(nums[1] - target);
return Math.min(diff1, diff2);
}
Arrays.sort(nums);
int closestSum = nums[0] + nums[1] + nums[nums.length - 1];
for (int i = 0; i < nums.length; i++) {
if (i - 1 >= 0 && nums[i] == nums[i - 1]) {
continue;
}
int left = i + 1;
int right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum > target) {
right--;
} else if (sum < target){
left++;
} else {
return sum;
}
int diffOld = Math.abs(closestSum - target);
int diffNew = Math.abs(sum - target);
if (diffNew < diffOld) {
closestSum = sum;
}
}
}
return closestSum;
}
}