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; };
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter