Why do we need
hash[number] = index
in the following code?
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
iteration does:
nums[0] is 11: target - number = 2 hash[2] doesn't exist --> we should be able to just forget about this number as number 11 at index 0 can not be part of the solution
nums[1] is 8: target - number = 1 hash[1] DOES exist and we use it's index (hash[1] = 2 ) as well as the current index (hash[8] = 1 ). --> this is our solution and will be returned at
return [complement, index]
the answer I keep getting on why
hash[number] = index
is needed is something on the lines of: "The line hash[number] = index assigns the index of the current number to the hash keyed by the current number. This is important because it allows the function to match the current number with a later number that, together, will add up to the target."
but since we get our result in
return [complement, index]
it seems unnecessary to me to add this line?
Answering my own question after reading through the answer comments (thank you for these!!)
Ask was: output the index of nums of the 2 numbers that add up to the target number.
hash is initially blank and needs to be populated via the else statement in.each
at num[0]: target - num[0] = 9-11 = -2. hash[-2] --> false, hence we move to else statement and populate hash with: hash[11] = 0
at num[1]: target - num[1] = 9-8 = 1. hash[1] --> false, hence we move to else statement and populate hash with: hash[8] = 1
at num[2]: target - num[2] = 9-1 = 8. hash[8] --> true, hence we return index of hash[8] and current index of num.each iteration = [1, 2]
at num[3]: target - num[3] = 9-7 = 2. hash[2] --> false, hence we move to else statement and populate hash with: hash[2] = 3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.