# 最接近的三数之和

给定一个包括  n 个整数的数组  nums  和 一个目标值  target。找出  nums  中的三个整数,使得它们的和与  target  最接近。返回这三个数的和。假定每组输入只存在唯一答案。

示例:

输入:nums = [-1,2,1,-4], target = 1
输出:2
解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。

提示:

3 <= nums.length <= 10^3
-10^3 <= nums[i] <= 10^3
-10^4 <= target <= 10^4

官方题解

// 整体的思路跟求三数之和差不多
/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
var threeSumClosest = function (nums, target) {
  nums = nums.sort((a, b) => a - b)
  const length = nums.length
  let res = 100000

  for (let first = 0; first < length; first++) {
    if (first > 0 && nums[first] === nums[first - 1]) continue

    let second = first + 1,
      third = length - 1

    while (second < third) {
      const sum = nums[first] + nums[second] + nums[third]
      if (Math.abs(sum - target) < Math.abs(res - target)) {
        res = sum
      }
      if (sum > target) {
        third--
        while (second < third && nums[third] === nums[third + 1]) third--
      } else {
        second++
        while (second < third && nums[second] === nums[second - 1]) second++
      }
    }
  }

  return res
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34