在Ruby中使用2 sum算法。
我已经启动了哈希t然后在每个迭代器中我试图检查t中是否存在密钥。出于某种原因,if语句似乎永远不会将t [target-n]评估为true,如果我在else部分中添加它。
def two_sum(nums, target)
t={}
a=[]
nums.each do |n|
if t[target-n]
a << nums.index(n)
a << nums.index(t[target-n])
return a
else
t[target-n] = n
end
end
end
如果您在循环开始时打印此调试行p "#{target-n}, #{t}"
,您可以找出原因。
...
nums.each do |n|
p "#{target-n}, #{t}"
...
使用此调用two_sum([3, 5, 2, -4, 8, 11], 7)
您将被打印:
# "4, {}"
# "2, {4=>3}"
# "5, {4=>3, 2=>5}"
# "11, {4=>3, 2=>5, 5=>2}"
# "-1, {4=>3, 2=>5, 5=>2, 11=>-4}"
# "-4, {4=>3, 2=>5, 5=>2, 11=>-4, -1=>8}"
如您所见,您要查找的密钥是由代码的else
部分添加的。
一种可能的选择(暴力)是建立对的散列,跳过重复的对。然后迭代填充数组a的散列,如果nums
中的每个对。
最后,通过该方法返回a
。
def two_sum(nums, target)
t={}
a=[]
nums.each do |n|
t[target-n] = n unless t[n]
end
t.each { |k,v| a << [k,v] if nums.include? k }
a
end