【问题标题】:Ruby each_with_index iteration. Unsure about why else statement is neededRuby each_with_index 迭代。不确定为什么需要 else 语句
【发布时间】:2023-01-20 22:18:53
【问题描述】:

为什么我们需要

hash[number] = index

在下面的代码中?

nums = [11, 8, 1, 7]
target = 9

def two_sum(nums, target)
  hash = {}

  nums.each_with_index do |number, index|
    if complement = hash[target - number]
      return [complement, index]
    end
    hash[number] = index
  end
end

迭代确实:

  • nums[0] 是 11: 目标 - 数字 = 2 hash[2] 不存在 --> 我们应该能够忘记这个数字,因为索引 0 处的数字 11 不能成为解决方案的一部分

  • nums[1] 是 8: 目标 - 数字 = 1 hash[1] 确实存在,我们使用它的索引 (hash[1] =2个) 以及当前索引 (hash[8] =1个). --> 这是我们的解决方案,将在

return [complement, index]

我不断得到的答案为什么

hash[number] = index

需要的是以下几行:“hash[number] = index 行将当前数字的索引分配给以当前数字为键的散列。这很重要,因为它允许函数将当前数字与以后的数字相匹配这些数字加起来就达到了目标。”

但是因为我们得到了结果

return [complement, index]

我似乎没有必要添加这一行?

【问题讨论】:

  • (1) 描述该方法应该做什么会有所帮助(对我们,也可能对您)。 (2) 如果你不在hash 中放入任何东西,hash[target - number] 怎么会给你任何东西? (3) 如果在nums 中没有找到您要查找的内容,应该怎么办?
  • 这有很多问题,但最初我注意到:“哈希 [1] 确实存在”.不,当你到达nums[1]时,它不会,nums[2]还没有实现,因此hash[1]不存在.然而,迭代 3 将返回 [1,2],因为 complement = hash[target - number] 变为 hash[9-1] 并且 hash[8] 确实存在并返回 1(它的索引)并且当前索引将为 2。如果没有 hash[number] = index,这将不是真的,这方法将始终返回 nums 数组。
  • 是的,更多细节会更好。谢谢你们的帮助——我设法理解了我的想法错在哪里——我错误地认为散列被填充了,但我们只在 else 语句中填充它。现在说得通了。谢谢你!

标签: ruby each


【解决方案1】:

阅读答案 cmets 后回答我自己的问题(谢谢你!!)

要求是:输出加起来等于目标数字的 2 个数字的 nums 索引。

hash 最初是空白的,需要通过 .each 中的 else 语句填充

  • 在 num[0]:目标 - num[0] = 9-11 = -2。 hash[-2] --> false,因此我们转到 else 语句并使用以下内容填充哈希:hash[11] = 0

  • 在 num[1]: target - num[1] = 9-8 = 1.hash[1] --> false,因此我们转到 else 语句并使用以下内容填充哈希:hash[8] = 1

  • at num[2]: target - num[2] = 9-1 = 8.hash[8] --> true,因此我们返回 hash[8] 的索引和 num.each iteration = [1, 2] 的当前索引]

  • 在 num[3]: target - num[3] = 9-7 = 2.hash[2] --> false,因此我们转到 else 语句并使用以下内容填充哈希:hash[2] = 3

【讨论】:

    猜你喜欢
    • 2011-06-17
    • 2016-08-10
    • 1970-01-01
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多