所以我试图找到我的两个总和问题的解决方案但我被卡住了,我需要打印加起来到目标的元素的索引,如果它是一半,我的解决方案将返回一个元素两次目标
def two_sum(nums, target)
num_hash = Hash.new(0)
nums.each_with_index do |num,idx|
num_hash[num] = idx
if num_hash.key?(target - num) && target % num != 0
return [num_hash[num], idx]
end
end
end
最佳答案
所以我认为问题与目标的 1/2 的数字无关,它似乎只是“如果找到解决方案,它会返回相同的索引两次”。例如,使用样本集 [2, 7, 11, 15]
two_sum([2, 7, 11, 15], 14) # => [2, 7, 11, 15]
因此,7
是目标 14
的一半,而不是像您建议的那样返回索引 1
两次会,它会返回原始输入数组(nums.each_with_index
的结果。但是,如果我们尝试传递 9
的目标,它的行为将如您所述:
two_sum([2, 7, 11, 15], 9) # => [1, 1]
之所以这样,是因为这条线:
return [num_hash[num], idx]
您已经将 num
设置为 num_hash
(num_hash[num] = idx
) 然后您将同时返回 idx
和 num_hash[num]
,也就是 idx
。所以你想要做的是:
return [num_hash[target - num], idx]
然后在未找到结果时“修复”返回的所有元素,只需在方法末尾返回 []
:
def two_sum(nums, target)
num_hash = Hash.new(0)
nums.each_with_index do |num,idx|
num_hash[num] = idx
if num_hash.key?(target - num) && target % num != 0
return [num_hash[target - num], idx]
end
end
[]
end
现在:
two_sum([2, 7, 11, 15], 14) # => []
two_sum([2, 7, 11, 15], 9) # => [0, 1]
注意:您的代码也有问题,如果您有两次相同的数字,它找不到答案:
two_sum([2, 7, 11, 7, 15], 14) # => []
留给你去弄清楚,只是想向你指出这一点。
关于ruby - 我怎样才能避免在我的两个总和解决方案中使用相同的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45899770/