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

第十六题 - 最接近的三数之和 #17

Open
laizimo opened this issue May 29, 2020 · 0 comments
Open

第十六题 - 最接近的三数之和 #17

laizimo opened this issue May 29, 2020 · 0 comments

Comments

@laizimo
Copy link
Owner

laizimo commented May 29, 2020

题目描述

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

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

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

算法

双指针法

答案

/**
 * 双指针法
 */
var threeSumClosest = function(nums, target) {
    // #1 数组排序
    nums = nums.sort((a, b) => a - b);
    // #2 取第一个数
    let ans = nums[0] + nums[1] + nums[2];
    for (let i = 0; i < nums.length ; i++) {
        // #3 设定两个指针
        let start = i + 1, end = nums.length - 1;
        while (start < end) {
            // #4 求和
            let sum = nums[start] + nums[end] + nums[i];
            // #5 比较绝对值大小
            if (Math.abs(sum - target) < Math.abs(ans - target)) ans = sum;
            // #6 如果相等,直接返回
            if (sum === target) return ans;
            // #7 根据sum大小来缩进两边指针
            sum > target ? end-- : start++;
        }
    }
    return ans;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant