3Sum Closest - LeetCode

PHOTO EMBED

Thu Oct 13 2022 15:55:24 GMT+0000 (Coordinated Universal Time)

Saved by @j_jivan #javascript

var threeSumClosest = function (nums, target) {
    /// [4, 0, 5, -5, 3, 3, 0, -4, -5], -2)
    
    let sum = Number.MAX_SAFE_INTEGER;
    let min_diff = Number.MAX_SAFE_INTEGER;
    nums.sort((a, b) => a - b);
    // -5, -5, -4, 0, 0, 3, 3, 4, 5  O(n^2)
    
    for (let i = 0, j = 1, k = nums.length - 1; i < nums.length - 2; ++i){
        while (j < k) {
            const currSum = nums[i] + nums[j] + nums[k];
            const diff = Math.abs(target - currSum);
            if (diff < min_diff) {
                min_diff = diff;
                sum = currSum;
            }
            if (target === currSum) {
                return target;
            } else if (currSum < target) {
                j++;
            } else {
                k--;
            }
        }
        j = i + 2;
        k = nums.length - 1;
    }
    return sum;
};
content_copyCOPY

3Sum Closest

https://leetcode.com/submissions/detail/821666591/