可以使用双指针法来解决这个问题。首先将数组排序,然后固定一个数,然后使用双指针来寻找另外两个数,使它们的和最接近目标值。

具体实现如下:

function threeSumClosest(nums, target) {
  nums.sort((a, b) => a - b); // 排序
  let closest = Infinity;

  for (let i = 0; i < nums.length - 2; i++) {
    let left = i + 1,
      right = nums.length - 1;

    while (left < right) {
      const sum = nums[i] + nums[left] + nums[right];

      if (Math.abs(sum - target) < Math.abs(closest - target)) {
        closest = sum;
      }

      if (sum > target) {
        right--;
      } else if (sum < target) {
        left++;
      } else {
        return closest;
      }
    }
  }

  return closest;
}

这个函数的时间复杂度是 O(n²),其中 n 是数组的长度。

JavaScript 实现三数之和最接近目标值

原文地址: https://www.cveoy.top/t/topic/mkZm 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录