so I followed a tutorial to learn how to complete 2 sum and I understand what ever line means but I dont understand why "diffs[list[i]]" returns the 0 index. I went through the the algorithm with the current arguments and i comes out to 3 when it returns the indexes
diffs = {} # Make a hash map to store values
for i in range(len(list)): # Iterate through list
if list[i] in diffs: # If the number you are on is in the has map
return [diffs[list[i]], i] # return indexes
else:
diffs[target - list[i]] = i
print(twosum([2, 11, 15, 7], 9))```
CodePudding user response:
def twosum(nums, target):
diffs = {} # Make a hash map to store values
for i in range(len(nums)): # Iterate through list
if nums[i] in diffs: # If the number you are on is in the has map
return [diffs[nums[i]], i] # return indexes
else:
diffs[target - nums[i]] = i
print(i, diffs)
In [4]: print(twosum([2, 11, 15, 7], 9))
0 {7: 0}
1 {7: 0, -2: 1}
2 {7: 0, -2: 1, -6: 2}
[0, 3]
As you can see from the above output, 7
has index 0
in the dictionary. It's the first element that is added to the dictionary. The reason is that you are saving the differences in the dictionary. target - nums[0]
is 7
in this case because nums[0]
is 2
.
Then, when you reach the last element, namely 7
, you find it in the dictionary with the index 0
. That is diffs[nums[3]] == diffs[7] == 0
. And you return [diffs[nums[i]], i] == [diffs[nums[3]], 3] == [diffs[7], 3] == [0, 3]
.
Also, don't use the name list
to name your variables.
CodePudding user response:
On the first run of the loop. diffs[target - list[i]] = i
sets diffs to {7: 0}. That's how diffs[list[3]] evaluates to 0. Eg.
diffs[list[3]]
diffs[7]
0