Created
October 21, 2017 10:36
-
-
Save Beraliv/338595a54ca7e4cef5b65b381c3da65c to your computer and use it in GitHub Desktop.
Get all number pairs which [[a, b], a + b = value], for a given value
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
function findPairsInSorted(arr, value) { | |
let results = []; | |
let len = arr ? arr.length : 0; | |
if (len < 2) { | |
return results; | |
} | |
for (let i = 0, j = len - 1; i < j;) { | |
let diff = value - arr[i]; | |
if (diff < arr[j]) { | |
j--; | |
} | |
else if (diff > arr[j]) { | |
i++; | |
} | |
else { | |
results.push([arr[i++], arr[j--]]); | |
} | |
} | |
return results; | |
} | |
function solve(arr, value) { | |
let sortedArr = arr.sort((a, b) => a - b); | |
return findPairsInSorted(sortedArr, value); | |
} | |
solve([ 3, 4, 5, -2, 10, 11, 12, -1, 0, 7, 8 ], 10); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment