Skip to content

Instantly share code, notes, and snippets.

@lienista
Last active October 11, 2018 22:54
Show Gist options
  • Select an option

  • Save lienista/441a851c4269415c0f040cf1276212bb to your computer and use it in GitHub Desktop.

Select an option

Save lienista/441a851c4269415c0f040cf1276212bb to your computer and use it in GitHub Desktop.
(Algorithms in Javascript) Leetcode 16. 3Sum Closest - 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.
const threeSumClosest = (nums, target) => {
let len = nums.length, sum=0;
if(len === 0) return 0;
if(len <= 3) {
for(let i=0; i<len; i++){
sum += nums[i];
}
return sum;
}
nums.sort(function(a,b){
return a-b;
});
let closest = nums[0]+nums[1]+nums[2];
for(let i=0; i<len; i++){
for(let j=i+1, k=len-1; j<len-1, j<k; ){
var sum = nums[i] + nums[j] + nums[k];
if(sum === target){
return sum;
} else if(sum<target){
if((closest<sum && sum<target) ||
Math.abs(target-sum)<Math.abs(target-closest)){
closest = sum;
}
j++;
} else if(sum>target){
if(closest>sum && sum>target ||
Math.abs(target-sum) < Math.abs(target-closest)) {
closest = sum;
}
k--; //to reduce sum decrease tail
}
}
}
return closest;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment