算法-最接近的三数之和

leetcode-最接近的三数之和
https://leetcode-cn.com/problems/3sum-closest/
坚持每天进步

最接近的三数之和

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

示例:

1
2
输入: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

解题思路

  • 定义双指针,避免暴力循环解题;
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
35
36
37
38
39
40
41
/**
* @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--;
}
}
}

return res;
};