Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target.
O(n^2) Two pointer solution
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var threeSumClosest = function(nums, target) {
nums.sort((a, b) => a - b);
// res is initialized as -Infinity, so we know there must be a number that is closer.
let res = -Infinity;
for(let i = 0; i < nums.length; i++) {
let low = i + 1, high = nums.length - 1;
while(low < high) {
let sum = nums[i] + nums[low] + nums[high];
if(Math.abs(sum - target) < Math.abs(res - target)) {
res = sum;
}
if(sum < target) {
low++;
} else {
high--;
}
}
}
return res;
};
