【问题标题】:ruby - what is wrong with the following array and target sum code?ruby - 以下数组和目标总和代码有什么问题?
【发布时间】:2026-01-26 06:00:01
【问题描述】:

二和

  1. 定义一个方法two_sum,它接受一个数组和一个目标总和(整数)作为参数。
  2. 如果数组中的任意两个整数与目标相加,则该方法应返回 true。
  3. 否则,它应该返回 false。假设数组只包含整数。

def two_sum(array, target)
    i = 0
    sum = []
    while i < array.max
        i = i + 1
        b = i + i
        sum.push(b)
    end
    sum.include?(target)
end

puts "------Two Sum------"

puts two_sum([1,2,3,4,5,6], 8) == true     #(im getting true)

puts two_sum([1,2,3,4,5,6], 18) == false   #(im getting true)

puts two_sum([1,3,6], 6) == false          #(im getting false)

puts two_sum([1,8,2,1], 0) == false        #(im getting true)

【问题讨论】:

    标签: arrays ruby loops debugging sum


    【解决方案1】:

    这是一种在性能很重要时加快计算速度的尝试,尤其是当数组很大并且包含许多重复值时。

    代码

    require 'set'
    
    def two_sum(arr, target)
      return true if target.even? && arr.count(target/2) > 1
      st = Set.new
      arr.uniq.each do |n|
        return true if st.include?(target-n)
        st << n
      end
      false
    end
    

    示例

    two_sum [1, 4, -4, 4, 5], 6  #=> true
    two_sum [1, 3, -4, 3, 4], 6  #=> true
    two_sum [1, 3, -4, 3, 5], 5  #=> false
    

    说明

    target 偶数值的代码有两个用途:

    • 当数组包含的值等于target 的二分之一并且该值在数组中至少出现两次时,它会缩短计算;和
    • 如果上述代码不返回true,它允许在执行剩余计算之前删除arr 中的重复值。

    对于第一个示例,步骤如下。

    arr = [1, 4, -4, 4, 5]
    target = 6
    
    target.even?
      #=> 6.even? => true
    arr.count(target/2) > 1
      #=> arr.count(3) > 1
      #=> 1 > 1
      #=> false
    

    所以true 不会返回。

    st = Set.new
      => #<Set: {}>
    b = arr.uniq
      #=> [1, 4, -4, 5]
    

    b 的第一个元素现在被传递给块。

    n = 1
    st.include?(target-n)
      #=> st.include?(6-1) => false as the set is empty
    st << n
      #=> #<Set: {1}>
    

    接下来的步骤如下。

    n = 4
    st.include?(target-n)
      #=> st.include?(6-4) => false
    st << n
      #=> #<Set: {1, 4}>
    
    n = -4
    st.include?(target-n)
      #=> st.include?(6-(-4)) => false
    st << n
      #=> #<Set: {1, 4, -4}>
    
    n = 5
    st.include?(target-n)
      #=> st.include?(6-5) => true
    

    所以true 被返回。

    【讨论】:

      【解决方案2】:

      ruby 解决方案如下所示:

      def two_sum(array, target)
        array.combination(2).any? { |v| v.reduce(:+) == target }
      end
      

      Array#combination 返回两个元素的所有组合,Enumerable#any? 返回 true,如果块计算为 true,否则返回 false

      【讨论】:

      • 考虑写块{ |a,b| a+b == target }
      • @CarySwoveland 不;我确实故意使用reduce:这样更改代码以使用,例如,3 的组合就像将2 更改为3 一样简单。
      • { |v| v.sum == target }呢?
      【解决方案3】:

      循环遍历数组的每个元素,这是一个好的开始。在这个循环中,您需要尝试将每对元素相加。目前,您向 sum 数组推送的所有内容都是 i+i:索引加倍(即从 0 到数组最大元素的每个偶数)。

      您可以尝试通过两个循环来对每对元素求和,一个循环在另一个循环中。他们都会遍历数组的元素。在您的内部循环中,您将尝试将外部循环中的当前元素添加到内部循环中的当前元素。如果你得到任何匹配,你可以返回 true 并立即退出;否则返回假。

      【讨论】: