3 Sum Closest
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You
- Time: O(n^2)
- Space: O(1)
public int threeSumClosest(int[] nums ,int target) {
Arrays.sort(nums);
int n = nums.length, closest = Integer.MAX_VALUE;
for (int i = 0; i < n - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
int l = i + 1, r = n - 1;
while (l < r) {
int sum = nums[i] + nums[l] + nums[r];
if (closest == Integer.MAX_VALUE ||
Math.abs(closest - target) > Math.abs(sum - target)) {
closest = sum;
}
if (sum == target) {
return target;
} else if (sum > target) {
r--;
} else {
l++;
}
}
}
return closest;
}