Skip to content

Instantly share code, notes, and snippets.

@aire-con-gas
Last active November 28, 2018 13:31
Show Gist options
  • Save aire-con-gas/9996a52b6a852119c8e6bc025f7d2c53 to your computer and use it in GitHub Desktop.
Save aire-con-gas/9996a52b6a852119c8e6bc025f7d2c53 to your computer and use it in GitHub Desktop.
JS Bin// source https://jsbin.com/loxeroh
/**
*/
"use strict";
var threeSumClosest = function threeSumClosest(num, target) {
var result = num[0] + num[1] + num[num.length - 1];
num.sort();
for (var i = 0, il = num.length - 2; i < il; i++) {
var start = i + 1;
var end = num.length - 1;
while (start < end) {
var sum = num[i] + num[start] + num[end];
if (sum > target) {
end--;
} else {
start++;
}
if (Math.abs(sum - target) < Math.abs(result - target)) {
result = sum;
}
}
}
return result;
};
console.log(threeSumClosest([-1, 2, 1, -4], 1));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment