Created
February 18, 2019 05:08
-
-
Save dlucidone/973960cb93f5b3d2b6bb1214cc2ce7ca to your computer and use it in GitHub Desktop.
tripplets sum
This file contains 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
// Time complexity: O(n^2) | |
function findTriplets(arr, n) { | |
arr.sort(); | |
var l = arr.length; | |
for (var i = 0; i < l; i++) { | |
var j = i + 1, | |
k = l - 1; | |
while (j < k) { | |
if (arr[i] + arr[j] + arr[k] < n) { | |
j++; | |
} else if (arr[i] + arr[j] + arr[k] > n) { | |
k--; | |
} else { | |
console.log(arr[i] + "," + arr[j] + "," + arr[k]); | |
j++; | |
k--; | |
} | |
} | |
} | |
return true; | |
} | |
var arr = [-1, -4, -9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; | |
findTriplets(arr, 0); | |
//http://geniuscarrier.com/finding-all-unique-triplets-that-sums-to-zero-javascript/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment