【发布时间】:2020-05-01 22:57:02
【问题描述】:
我正在处理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
代码有效,但是,我不太确定为什么会这样。
所以我知道在每个语句中它都会遍历数字并找到差异。例如,
nums = [4,2,5,1]
target = 6
在第一个循环中,差值是 6-2 = 4。但是哈希显然是空的,所以它会将 num 注册为键,以当前索引作为值。因此哈希是,
hash = {
4: 0
}
在第二个循环中,差异为 6-4 = 2。hash[4] 为 nil,因此它将当前的 num 和索引添加到字典中。
hash = {
4: 0
2: 1
}
像这样,这不会一直将 nums 添加到哈希中,因为至少在这种情况下没有匹配的键值对吗?
也许我把事情复杂化了。如果有人可以 eli5,我将不胜感激。谢谢!
【问题讨论】:
-
如果没有一对数字总和为
target,则返回nums,因此您可以添加nil作为倒数第二行。您也可以将if/else/end结构替换为return [hash[diff], index] if hash.key?(diff); hash[num] = index。 -
短而甜,虽然效率不高:
nums.each_index.to_a.combination(2).find { |i,j| nums[i]+nums[j] == target }。
标签: ruby