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

16. 最接近的三数之和 #10

Open
webVueBlog opened this issue Aug 30, 2022 · 0 comments
Open

16. 最接近的三数之和 #10

webVueBlog opened this issue Aug 30, 2022 · 0 comments

Comments

@webVueBlog
Copy link
Owner

16. 最接近的三数之和

Description

Difficulty: 中等

Related Topics: 数组, 双指针, 排序

给你一个长度为 n 的整数数组 nums和 一个目标值 target。请你从 nums中选出三个整数,使它们的和与 target 最接近。

返回这三个数的和。

假定每组输入只存在恰好一个解。

示例 1:

输入:nums = [-1,2,1,-4], target = 1
输出:2
解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。

示例 2:

输入:nums = [0,0,0], target = 1
输出:0

提示:

  • 3 <= nums.length <= 1000
  • -1000 <= nums[i] <= 1000
  • -104 <= target <= 104

Solution

Language: JavaScript

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

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

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

No branches or pull requests

1 participant