Question:

Given an array nums of n integers 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. Given array nums = [-1, 2, 1, -4], and target = 1.
  2. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

Solution:

  1. /**
  2. * @param {number[]} nums
  3. * @param {number} target
  4. * @return {number}
  5. */
  6. var threeSumClosest = function(nums, target) {
  7. if(nums.length<3||nums==null) return -1;
  8. nums.sort((a,b) => a - b);
  9. let closeNum = nums[0] + nums[1] + nums[2];
  10. for (let i = 0; i < nums.length - 2; i++) {
  11. let left = i + 1;
  12. let right = nums.length - 1;
  13. while (left < right) {
  14. let sum = nums[left] + nums[right] + nums[i];
  15. if (Math.abs(sum - target) < Math.abs(closeNum - target)) {
  16. closeNum = sum;
  17. }
  18. if (sum < target) {
  19. left ++;
  20. } else {
  21. right --;
  22. }
  23. }
  24. }
  25. return closeNum;
  26. }

Runtime: 68 ms, faster than 75.96% of JavaScript online submissions for 3Sum Closest.