Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

最接近的三数之和 #7

Open
bWhirring opened this issue Dec 24, 2019 · 2 comments
Open

最接近的三数之和 #7

bWhirring opened this issue Dec 24, 2019 · 2 comments
Labels

Comments

@bWhirring
Copy link
Owner

给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。

例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.

与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum-closest
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
@bWhirring
Copy link
Owner Author

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
var threeSumClosest = function(nums, target) {
  const len = nums.length
  if (len === 3) return nums.reduce((a, b) => a + b)
  nums = nums.sort((a, b) => a - b)
  let sum = nums[0] + nums[1] + nums[2]

  for (let i = 0; i < len; i++) {
    let l = i + 1
    let r = len - 1
    while (l < r) {
      const current = nums[i] + nums[l] + nums[r]
      if (Math.abs(current - target) < Math.abs(sum - target)) {
        sum = current
      }
      if (current > target) {
        r--
      } else if (current < target) {
        l++
      } else {
        return current
      }
    }
  }
  return sum
};

@bWhirring
Copy link
Owner Author

bWhirring commented Dec 24, 2019

与三数之和类似 #6

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant