Ruby on rails TwoSum |预期值为[0,1],而实际值为[0,0]| Ruby indexs';问题

Ruby on rails TwoSum |预期值为[0,1],而实际值为[0,0]| Ruby indexs';问题,ruby-on-rails,Ruby On Rails,输出 two_sum([2, 2, 3], 4) 我怎样才能解决这个问题?我试过用杂烩做点什么。。。我也很感激任何关于如何使我的代码更简洁的建议,因为我是初学者/ Expected: [0, 1], instead got: [0, 0] 这部分已经改变了!我添加了hash以简化索引,然后添加了if语句,如果两个索引相同,则向第二个索引添加+1。我假设,给定一个整数数组num和一个整数tg,您希望找到一对不同的索引I和j,这样num[I]+num[j]==tg为true。(重要的是,每一个问

输出

two_sum([2, 2, 3], 4)
我怎样才能解决这个问题?我试过用杂烩做点什么。。。我也很感激任何关于如何使我的代码更简洁的建议,因为我是初学者/

Expected: [0, 1], instead got: [0, 0]

这部分已经改变了!我添加了hash以简化索引,然后添加了if语句,如果两个索引相同,则向第二个索引添加+1。

我假设,给定一个整数数组
num
和一个整数
tg
,您希望找到一对不同的索引
I
j
,这样
num[I]+num[j]==tg
true
。(重要的是,每一个问题都要以对问题的准确陈述开始。)

让我们先看看为什么会得到不正确的结果

  h = (0..nums.size).map(&:to_i)
  h = h.zip(nums).to_h
  o = [h.key(c[0]), h.key(c[1])]
  o[0] == o[1] ? o[1]+1 : o
计算后

x1.combination(2).to_a
  #=> [[2, 2], [2, 3], [2, 3]]
然后

x2 = b.reject { |x| x.sum != tg }
  #=> [[2, 2]]
c = x2[0]
  #=> [2, 2]
我们看到的问题是,在计算
x3
x4
时,我们寻找第一个索引
i
,使得
nums[i]
等于
2
,两者都为零

解决此问题的一种方法是在计算
x4
时使用:

x3 = nums.index(c[0])
  #=> nums.index(2) => 0
x4 = nums.index(c[1])
  #=> nums.index(2) => 0
[x3, x4]
  #=> [0, 0]

现在让我们看看如何改进这个答案。关键是,尽管
nums
可能包含重复的值,但是
nums
值的索引数组
[0,1,2]
不包含重复的值。因为我们想要的是索引,所以最容易从这些索引开始,根据需要计算每个索引的
num[i]

x4 = nums.rindex(c[1])
  #=> nums.rindex(2) => 1
a
可通过多种方式获得
nums。每个索引到a
nums.size.times.to a
是两个。此外,这两个操作可能是链接的:

a = (0..nums.size-1).to_a
  #=> [0, 1, 2] 
a.combination(2).find { |i,j| nums[i] + nums[j] == tg }
  #=> [0, 1]
如果愿意,为了避免查找
num[i]

nums.each_index.to_a.combination(2).find { |i,j| nums[i] + nums[j] == tg }
一些红宝石学家可能会选择写这篇文章

a = nums.each_with_index.to_a
  #=> [[2, 0], [2, 1], [3, 2]]
a.combination(2).find { |(ni,_i),(nj,_j)| ni + nj == tg }.map(&:last)
  #=> [0, 1]

我已经利用Ruby来表达块变量。这比

nums.each_with_index.
     to_a.
     combination(2).
     find { |(ni,_i),(nj,_j)| ni + nj == tg }.
     map(&:last)
我已将块中的两个索引命名为以下划线(
\u I
\u j
)开头,以向读者表明它们未用于块计算。这是一个常见的Ruby约定。单独使用下划线可能更常见(尽管可以说不太具描述性):
|(ni,|),(nj,|)

map(&:last)
map{n,i}
的缩写

x3 = nums.index(c[0])
  #=> nums.index(2) => 0
x4 = nums.index(c[1])
  #=> nums.index(2) => 0
[x3, x4]
  #=> [0, 0]
x4 = nums.rindex(c[1])
  #=> nums.rindex(2) => 1
a = (0..nums.size-1).to_a
  #=> [0, 1, 2] 
a.combination(2).find { |i,j| nums[i] + nums[j] == tg }
  #=> [0, 1]
nums.each_index.to_a.combination(2).find { |i,j| nums[i] + nums[j] == tg }
a = nums.each_with_index.to_a
  #=> [[2, 0], [2, 1], [3, 2]]
a.combination(2).find { |(ni,_i),(nj,_j)| ni + nj == tg }.map(&:last)
  #=> [0, 1]
nums.each_with_index
    .to_a
    .combination(2)
    .find { |(ni,_i),(nj,_j)| ni + nj == tg }
    .map(&:last)
nums.each_with_index.
     to_a.
     combination(2).
     find { |(ni,_i),(nj,_j)| ni + nj == tg }.
     map(&:last)
a.combination(2).find { |x1, x2| x1.first + x2.first == tg }.map(&:last)