/** * @param {number[]} nums * @param {number} target * @return {number} */ var threeSumClosest = function (nums, target) { nums = nums.sort((a, b) => (a - b)); let min = target; let res = 0; for (let len = nums.length, i = 0; i < len - 2; i++) { const currNum = nums[i]; let leftIndex = i + 1; let rightIndex = len - 1;
if (i === 0) { min = Math.abs(target - (currNum + nums[1] + nums[2])); }
while (leftIndex < rightIndex) { const sum = (currNum + nums[leftIndex] + nums[rightIndex]); const cha = target - sum; const chaAbs = Math.abs(cha);
if (chaAbs == 0) { res = sum; min = 0; break; } else if (chaAbs <= min) { min = chaAbs; res = sum; } if (cha > 0) { leftIndex++; } else if (cha < 0) { rightIndex--; } } }