例如,给定的整数 S = {-10 20 10 -40}, 目标值 = 10.
最接近目标值的和为 2. (-10 + 20 + 10 = 20).
/**
*
* @param num int整型一维数组
* @param target int整型
* @return int整型
*/
function threeSumClosest( num , target ) {
// write code here
num.sort((a,b) => a-b);//将数组从小到大排序
let len = num.length;
let res = num[0] + num[1] + num[len-1];//初始值设为第一个固定数加上左指针所指数和右指针所指数
for(let i = 0; i < len-2; i++){//固定数从第一个数循环到倒数第三个数,因为当固定数为倒数第三个数时,剩下两个数分别为左右指针所指数
let n1 = num[i];
let left = i+1;
let right = len-1;
while(left < right){
let n2 = num[left];
let n3 = num[right];
let sum = n1 + n2 + n3;
if(sum == target) return sum;
sum > target ? right--:left++;//如果三数之和大于target,右指针往左移,如果三数之和小于target,左指针往右移
if(Math.abs(sum - target) < Math.abs(res - target)){//判断sum与target差值是否变小,变小则更新res
res = sum;
}
}
}
return res;
}
module.exports = {
threeSumClosest : threeSumClosest
};