正如标题所述,我正在寻找两个总和等于目标整数的元素。我已经制定了下面的解决方案,但这只适用于唯一整数。涉及到重复值时,我遇到了问题。当然,我可以使用多个循环来记录两个单独的索引,并以这种方式确保这两个索引相同。但是,我想知道是否有一种方法可以通过一次迭代来解决这个问题。给定一个整数和目标数组,如果任意两个元素总和为目标,则返回true
two_sum([1,2,3,4,5,6], 8) = true
two_sum([4,4], 8) = false
def two_sum(array, target)
idx = 0
while idx < array.length
complement = target - array[idx]
if array.include?(complement) && complement != array[idx]
return true
end
idx+=1
end
return false
end
'array.combination(2).any? {| a,b | a + b == target}' – steenslag
我建议'array.combination(2).find {| a,b | a + b == target}',它返回所需的对或'nil'。编辑:Egad! @steenslag在我做之前几分钟内发布了几乎完全相同的评论,甚至是相同的块变量!我确实认为'find'比'any''更受欢迎,因为所需的一对是想要的。 –
@CarySwoveland从头部:“...如果任何两个元素总和为目标,则返回true”。 – steenslag