美文网首页
leetcode #16 3Sum Closest

leetcode #16 3Sum Closest

作者: huntriver | 来源:发表于2017-09-16 13:44 被阅读0次

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

        For example, given array S = {-1 2 1 -4}, and target = 1.
    
        The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
    
    • 题目大意
      与上一道题基本一样,只不过这回是找到3个数,使他们的和与给定的target最为相近。

    算法上与上一题类似,只不过我们不再需要去掉重复的数字

    /**
     * @param {number[]} nums
     * @param {number} target
     * @return {number}
     */
    var threeSumClosest = function(nums, target) {
      nums.sort((a, b) => a - b);
      let result = Number.MAX_VALUE;
      for (let i = 0; i < nums.length - 2; i++) {
        let j = i + 1;
        let k = nums.length - 1;
        while (j < k) {
          let sum=nums[i]+nums[j]+nums[k];
          if (Math.abs(result-target)>Math.abs(sum-target)) {  //判断是否相近
            result = sum;
            if (result === target) return result; //当找到3个数的和与target相同时 直接退出
          }
          if (sum>target) k--;
          else
            j++;
        }
      }
      return result;
    };
    
    

    相关文章

      网友评论

          本文标题:leetcode #16 3Sum Closest

          本文链接:https://www.haomeiwen.com/subject/kuwysxtx.html