Skip to content

Latest commit

 

History

History
40 lines (33 loc) · 1.32 KB

File metadata and controls

40 lines (33 loc) · 1.32 KB

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.

Screen Shot 2021-09-23 at 2 14 00 PM

O(n^2) Two pointer solution

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
var threeSumClosest = function(nums, target) {
    nums.sort((a, b) => a - b);
    // res is initialized as -Infinity, so we know there must be a number that is closer.
    let res = -Infinity;
    
    for(let i = 0; i < nums.length; i++) {
        let low = i + 1, high = nums.length - 1;
        while(low < high) {
            let sum = nums[i] + nums[low] + nums[high];
            if(Math.abs(sum - target) < Math.abs(res - target)) {
                res = sum;
            }
            if(sum < target) {
                low++;
            } else {
                high--;
            }
        }
    }
    return res;
};

Screen Shot 2022-09-02 at 20 52 54