Skip to content

Instantly share code, notes, and snippets.

@keegoo
Created July 14, 2020 15:12
Show Gist options
  • Save keegoo/297169ccca794b29560108c16addee55 to your computer and use it in GitHub Desktop.
Save keegoo/297169ccca794b29560108c16addee55 to your computer and use it in GitHub Desktop.

puzzle 01

# Description: 
# given a list of integer(no duplicate), find all pairs that add up to a target number
# example: list=[1,3,5,7] target=8, result = 1,7 3,5
# requirement: as fast as possible
require 'set'

def find_pair(ary, sum)
  res = []
  s = Set.new()
  ary.each {|x|
    left = sum - x
    if s.include?(left)
      res.push(Set.new([x, left]))
      s.delete(left)
    else
      s.add(x)
    end
  }

  return res
end

puts find_pair([1, 2 ,3, 6, 4, 8], 9)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment