2016-11-23 43 views
0

正如标题所述,我正在寻找两个总和等于目标整数的元素。我已经制定了下面的解决方案,但这只适用于唯一整数。涉及到重复值时,我遇到了问题。当然,我可以使用多个循环来记录两个单独的索引,并以这种方式确保这两个索引相同。但是,我想知道是否有一种方法可以通过一次迭代来解决这个问题。给定一个整数和目标数组,如果任意两个元素总和为目标,则返回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 

回答

0
def two_sum(array, target) 
    array.combination(2).each { |pair| return true if pair.inject(:+) == target } 
    return false; 
end 
+5

'array.combination(2).any? {| a,b | a + b == target}' – steenslag

+2

我建议'array.combination(2).find {| a,b | a + b == target}',它返回所需的对或'nil'。编辑:Egad! @steenslag在我做之前几分钟内发布了几乎完全相同的评论,甚至是相同的块变量!我确实认为'find'比'any''更受欢迎,因为所需的一对是想要的。 –

+1

@CarySwoveland从头部:“...如果任何两个元素总和为目标,则返回true”。 – steenslag

2
require 'set' 

def two_sum(arr, tot) 
    st = Set.new 
    arr.each { |n| st.include?(tot-n) ? (return true) : st << n } 
    false 
end 

two_sum [1,2,3,4,5,6], 8 #=> true 
two_sum [4,4], 8   #=> true 
two_sum [1,2,3,4,5,6], 3421 #=> false 

如果您愿意返回两个值是总和tot(当true),与[n, tot-n]替换true(或只返回n,另一个是tot - n)。

我使用了一个集合而不是一个数组来进行更快的查找。

+0

它是O(n)对O(n ** 2)。太好了! – pjs

相关问题