16. 3Sum Closest

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).

var threeSumClosest = function(nums, target) {
    var n = 0;
    var ans = 0;
    var sum;
    //排序
    nums.sort((a,b) => a-b);
    n = nums.length;
    //如果数组中不多于3个元素,则返回所有元素和
    if (nums.length <= 3) {
        for (let i = 0;i < n;i++) {
            ans += nums[i];
        }
        return ans;
    }
    //初始化记录和的变量
    ans = nums[0] + nums[1] + nums[2];
    //遍历每个元素
    for (let i = 0; i < n-2; i++) {
        //对于每个元素,我们首先将其后面的元素和整个的最后一个元素作为另外两个元素
        var j = i + 1;
        var k = n - 1;
        while (j < k) {
            sum = nums[i] + nums[j] + nums[k];
            //如果差距比当前记录的小,更新记录
            if (Math.abs(target - ans) > Math.abs(target - sum)) {
                ans = sum;
                if (ans == target) return ans;
            }
            //如果和大,就把最后一个元素往前挪一个
            //如果和小,就把第二个元素往后挪一个
            (sum > target) ? k-- : j++;
        }
    }
    return ans;
};

你可能感兴趣的:(16. 3Sum Closest)