Ruby solution for two sum in daily challenge Aug 2:
Code:
def two_sum(nums, target)
#two sum really?
# c = Hash.new do |h,k|
# p "h is #{h}, k is #{k}"
# h[k] = []
# end
# c = Hash.new {|h,k| h[k] = [] }
c = {}
nums.each_with_index do |num, index|
if !c[num]
c[num] = [index]
else
c[num] << index
end
end
c.each_pair do |k,v|
if c[target - k]
if k * 2 != target
return [v.first, c[target - k].first]
elsif k * 2 == target && v.length > 1
return v
end
end
end
endThe above one passed the test cases. But if use either commented out code (Hash initialization with empty array).
Got Error out for below test cases. Not sure about the cause.
If I made silly mistakes, let me know
[2,5,5,11]
10