Last active
November 28, 2018 13:31
-
-
Save aire-con-gas/9996a52b6a852119c8e6bc025f7d2c53 to your computer and use it in GitHub Desktop.
JS Bin// source https://jsbin.com/loxeroh
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
*/ | |
"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