0
Can someone explain to me how it works?
#On one site I met a task and the solution for it. This task is placed in easy level programming(. .) #Given an array of integers, return indices of the two numbers such that they add up to a specific target. #You may assume that each input would have exactly one solution, and you may not use the same element twice. #For example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. class Solution: def twoSum(self, nums, target): h = {} for i, num in enumerate(nums): n = target - num if n not in h: h[num] = i else: return [h[n], i]
3 Respostas
+ 3
You post the solution but not the task description. I am a bit puzzled about the return value.
Anyway it sort of goes like this. You have a list of numbers, and you want to figure out which two numbers add up to a specific target value.
x + y = target
This means also that
target - x = y
So the code puts the "distance" of each number from the target, into a dictionary, to mark its index position. Then loops over every number and if any of them is the same as one of the previously stored differences, that means the target sum is achieved.
If there is no match, the function returns None by default.
+ 3
There are other possible solutions for example you could build two nested loops and compare each list element with each list element to check for the target sum.
But this means a higher Time Complexity, I think O(n²), so with huge lists you can hit performance issues.
But the clever thing about the posted solution is that it only requires a single iteration over the list, that is O(n) complexity. And dictionary is a very efficient data structure (reading and writing does not require any internal looping over the dict, because keys are hashed). So this algorithm is extremely efficient... even if it is a little hard to comprehend at first.
0
oh, of course, sorry. I've added description in post)