[16] 最接近的三数之和

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
var threeSumClosest = function (nums, target) {
  nums.sort((a, b) => a - b);
  let ll = nums.length;
  let ans1 = nums[ll - 1] + nums[ll - 2] + nums[ll - 3];
  let ans2 = nums[0] + nums[1] + nums[2];

  for (let i = 0; i < ll - 1; i++) {
    if (i > 0 && nums[i] === nums[i - 1]) {
      i++;
      continue;
    }
    let left = i + 1;
    let right = ll - 1;
    while (right > left) {
      let cha = nums[i] + nums[left] + nums[right];
      if (cha === target) {
        return target;
      } else if (cha > target) {
        ans1 = Math.min(ans1, cha);
        right--;
      } else {
        ans2 = Math.max(ans2, cha);
        left++;
      }
    }
  }
  if (ans1 - target > target - ans2) {
    return ans2;
  } else {
    return ans1;
  }
};

 

posted @ 2023-11-27 13:42  人恒过  阅读(17)  评论(0)    收藏  举报