首页 > 试题广场 >

最接近的三数之和

[编程题]最接近的三数之和
  • 热度指数:12787 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
给出含有n个整数的数组s,找出s中和加起来的和最接近给定的目标值的三个整数。返回这三个整数的和。你可以假设每个输入都只有唯一解。
   例如,给定的整数 S = {-10 20 10 -40}, 目标值 = 10.
   最接近目标值的和为 2. (-10 + 20 + 10 = 20).
示例1

输入

[0,0,0],1

输出

0
/**
  * 
  * @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
};

编辑于 2020-08-19 21:49:15 回复(0)