-
Notifications
You must be signed in to change notification settings - Fork 68
/
SumofPairs.rb
73 lines (61 loc) · 1.61 KB
/
SumofPairs.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
=begin
Sum of Pairs
Given a list of integers and a single sum value, return the first two values
(parse from the left please) in order of appearance that add up to form the sum.
sum_pairs([11, 3, 7, 5], 10)
# ^--^ 3 + 7 = 10
== [3, 7]
sum_pairs([4, 3, 2, 3, 4], 6)
# ^-----^ 4 + 2 = 6, indices: 0, 2 *
# ^-----^ 3 + 3 = 6, indices: 1, 3
# ^-----^ 2 + 4 = 6, indices: 2, 4
# * entire pair is earlier, and therefore is the correct answer
== [4, 2]
sum_pairs([0, 0, -2, 3], 2)
# there are no pairs of values that can be added to produce 2.
== None/nil/undefined (Based on the language)
sum_pairs([10, 5, 2, 3, 7, 5], 10)
# ^-----------^ 5 + 5 = 10, indices: 1, 5
# ^--^ 3 + 7 = 10, indices: 3, 4 *
# * entire pair is earlier, and therefore is the correct answer
== [3, 7]
=end
# My Solution
def sum_pairs(ints, s)
result = []
new_ints = []
ints_hash = Hash.new {|value,key| value[key]=0}
ints.each do |x|
ints_hash[x] += 1
if ints_hash[x] < 3
new_ints << x
end
end
new_ints.each_with_index do |x,i|
(i+1).upto(new_ints.length-1) do |a|
if x + new_ints[a] == s
result << [x, new_ints[a]]
end
end
end
result != [] ? result.sort[0] : nil
end
# Better Solution
def sum_pairs(ints, s)
seen = {}
for i in ints do
return [s-i, i] if seen[s-i]
seen[i] = true
end
nil
end
# Another Solution
require 'set'
def sum_pairs(ints, s)
seen = Set.new
ints.each { |v|
return [s - v, v] if seen.include?(s - v)
seen << v
}
nil
end