16. 3Sum Closest(js)

16. 3Sum Closest

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
题意:给定一个数字数组和一个目标值,找到数组的三项相加最接近目标值,返回这三项
var threeSumClosest = function(nums, target) {
    let len=nums.length;
      //1.排序
      nums=nums.sort((a,b)=>a-b);  
      let res=nums[0]+nums[1]+nums[len-1];
    for(let i=0;i<len-2;i++){
        let sum=0;
        let start=i+1,end=len-1;
          while(start<end){
              sum=nums[i]+nums[start]+nums[end];
              if(sum<target) ++start;
              else --end;
              //比较大小
              if(Math.abs(sum-target)    < Math.abs(res-target)){
                  res=sum;
              }
          }
    }

    return res;
};
原文地址:https://www.cnblogs.com/xingguozhiming/p/10386357.html