leetcode-Medium-第12期-数组-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.

最接近的值: (-1 + 2 + 1 = 2).

  • 解法
var threeSumClosest = function(nums, target) {
  const len = nums.length
  let closest = nums[0] + nums[1] + nums[2]
  let diff = Math.abs(target - closest)
//将数组按照升序排列
  nums = nums.sort((a, b) => a - b);
  for(let i = 0; i < len - 2; ++i){
    let left = i + 1
    let right = len -1
    while(left < right){
      const sum =  nums[i] + nums[left] + nums[right]
      const newDiff = Math.abs(target - sum)
      if(diff > newDiff){
        diff = newDiff
        closest = sum
      }
      if(sum < target){
//和小于目标值,所以将left往右移一个,取得值更大一点(数组此时为升序
//这样与目标值的差距会更小一点
        left++ 

      }else{
        right--
      }
    }
  }
    return closest
};


  • 复习sort
var arr =  [ 7,6,15,4,13,2,1]
arr.sort() // 1,13,15,2,4,6,7并没有按照升序

因为无参数按照ascii码来排序每个元素的第一位,第二位不管。

所以按照升序排列:
arr.sort((a,b) => a - b)

你可能感兴趣的:(leetcode-Medium-第12期-数组-3Sum Closest)