给定一个整数和目标数组,如果任何两个元素总和为目标,则返回true

时间:2016-11-23 16:55:56

标签: ruby

正如标题所述,我希望找到两个元素,其总和等于目标整数。我已经解决了下面的解决方案,但这只适用于唯一的整数。在涉及重复值时,我遇到了问题。当然,我可以使用多个循环来跟踪两个单独的索引,并以这种方式确保这两个索引是相同的。但是,我想看看是否有办法通过一次迭代来解决这个问题。

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

2 个答案:

答案 0 :(得分: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时),请将true替换为[n, tot-n](或只返回{{ 1}},另一个是n)。

我使用了一个集合而不是一个数组来加快查找速度。

答案 1 :(得分:0)

rrule