16. 3Sum Closest

Problem


Tags: Array, Two Pointers, Sorting

Given an integer array nums of length n 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 1:

Input: nums = [-1,2,1,-4], target = 1
Output: 2
Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

Example 2:

Input: nums = [0,0,0], target = 1
Output: 0

Constraints:

  • 3 <= nums.length <= 1000
  • -1000 <= nums[i] <= 1000
  • -10^4 <= target <= 10^4

Code

JS

// 16. 3Sum Closest (10/16/53764)
// Runtime: 76 ms (78.81%) Memory: 40.58 MB (94.98%) 

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
function threeSumClosest(nums, target) {
    nums.sort((a, b) => a - b);

    let result = Infinity;
    for (let i = 0; i < nums.length - 2; i++) {
        if (i > 0 && nums[i] === nums[i - 1]) continue;
        let ptrL = i + 1,
            ptrR = nums.length - 1;
        while (ptrL < ptrR) {
            const sum = nums[i] + nums[ptrL] + nums[ptrR];
            if (sum === target) return sum; 
            else {
                if(Math.abs(sum - target) < Math.abs(result - target)) result = sum;
                if (sum < target) ptrL++;
                else ptrR--;
            }
        }
    }

    return result;
};