理解两个求和 leetcode 问题 (Ruby)

nin*_*get 3 ruby

我正在研究Leetcode Two Sums问题:“给定一个整数数组,返回两个数字的索引,使它们相加为特定目标。”。这就是我所拥有的:

def two_sum(nums, target)
  hash = {}
  nums.each_with_index do |num, index|
    diff = target - num
    if hash[diff]
      return [hash[diff],index]
    else
      hash[num] = index
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

该代码有效,但是,我不太确定为什么会这样。

所以我明白,在每个语句中,它遍历数字并找到差异。例如,

nums = [4,2,5,1]
target = 6
Run Code Online (Sandbox Code Playgroud)

在第一个循环中,差异是 6-2 = 4。但是哈希显然是空的,因此它将注册 num 作为键,以当前索引作为值。因此哈希是,

hash = {
  4: 0
}
Run Code Online (Sandbox Code Playgroud)

在第二个循环中,差异是 6-4 = 2。hash[4] 为 nil,因此它将当前 num 和 index 添加到字典中。

hash = {
  4: 0
  2: 1
}
Run Code Online (Sandbox Code Playgroud)

像这样,这不会继续将 nums 添加到哈希中,因为至少在这种情况下没有匹配的键值对吗?

也许我把事情复杂化了。如果有人可以 eli5,我将不胜感激。谢谢!

Ser*_*nin 6

诀窍是我们使用数字作为键将值添加到哈希中:

hash[num] = index
Run Code Online (Sandbox Code Playgroud)

但使用差异作为关键提取它:

if hash[diff]
Run Code Online (Sandbox Code Playgroud)

所以如果你有作为输入:

nums = [4,2,5,1]
target = 6
Run Code Online (Sandbox Code Playgroud)

然后在第一步,差异是 6 - 4 = 2,映射中没有键 2(差异),我们将键 4(数字)添加到映射中。第二步,差异是6 - 2 = 4,并且映射中已经有一个键4(差异),所以我们返回该值。