the map value you see is a lookup table, and the twoSum method implemented what is called dynamic programming
In dynamic programming, you store the values ββof your calculations, which you can use later to find a solution.
Let's see how it works in order to better understand this:
twoSum([10,20,40,50,60,70], 50)
In iteration 0:
the value is 10. Our target number is 50. When I see the number 10 in index 0, I note that if I ever find 40 (50 - 10 = 40) in this list, then I can find its pair in index 0 .
Thus, on our map 40 points to 0.
In iteration 2:
value 40. I look at the map my card to see that I previously found a pair for 40.
map[nums[x]] (the same as map[40] ) will return 0.
This means that I have a pair for 40 with index 0.
0 and 2 are a pair.
Does that make sense now?
Unlike your solution, where you have 2 nested loops, you can store previously calculated values. This will save you processing time, but consumes more memory space (because the lookup table will need memory)
Also, since you are writing this in javascript, your map may be an object, not an array. This will also make debugging a lot easier;)
source share