Last active
January 1, 2016 06:39
-
-
Save elreimundo/8106594 to your computer and use it in GitHub Desktop.
A program to determine all pairs of integers in a given array of integers that add to 100. The algorithm is destructive on the original array. This particular algorithm runs in N lg N time and constant space if the sorting algorithm is efficient; after the sort, only one additional pass through the array is required.
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
def hundred_pairs(array, target = 100) | |
array.sort! | |
results = [] | |
min, max = array.shift, array.pop | |
while min && max | |
while min + max > target | |
max = array.pop | |
end | |
while min && max && min + max < target | |
min = array.shift | |
end | |
if min && max && min + max == target | |
results << [min,max] | |
min, max = array.shift, array.pop | |
end | |
end | |
results | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment