Skip to content

Instantly share code, notes, and snippets.

@mayfer
Created October 22, 2014 19:03
Show Gist options
  • Save mayfer/978bb13040dc5581b1db to your computer and use it in GitHub Desktop.
Save mayfer/978bb13040dc5581b1db to your computer and use it in GitHub Desktop.
Find pairs of numbers that add up to the sum (three different methods)
# runtime O(N^2)
# memory O(1)
def find_pair(numbers, sum)
numbers.each_with_index do |n, i|
numbers.each_with_index do |m, j|
if n + m == sum
return [n, m]
end
end
end
return nil
end
# runtime O(N)
# memory O(N)
def find_pair(numbers, sum)
hash = {}
numbers.each_with_index do |n, i|
hash[n] = n
end
numbers.each_with_index do |n, i|
if hash.has_key?(sum-n)
return [n, sum-n]
end
end
return nil
end
# Assumption: Sorted numbers
# runtime O(N)
# memory O(1)
def find_pair(numbers, sum)
i = 0
j = numbers.length-1
while j >= 0 && i < numbers.length
if numbers[i] + numbers[j] > sum
j -= 1
elsif numbers[i] + numbers[j] < sum
i += 1
else
return [ numbers[i], numbers[j] ]
end
end
return nil
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment