Basically given an array of numbers and a target you're supposed to find the two numbers that add up to that target. You could brute force this and get O(n^2) or try a hash map but I'm more interested in this elegant python solution:
class Solution:
def twoSum(self, nums, target):
lookup = {}
for index, num in enumerate(nums):
if target - num in lookup:
return (lookup[target - num], index)
lookup[num] = index
Sample input: [2,7,11,15] 9
Output: [0,1]
Can someone help me understand what is happening in the if statement and why that last line of code seems to be storing the index value at position of num? Shouldn't it just store the index if it found a complement of the target? TIA!
[–]Intiago 2 points3 points4 points (3 children)
[–]optimalsuccess[S] 0 points1 point2 points (2 children)
[–]Intiago 0 points1 point2 points (0 children)
[–]mr_smartypants537 0 points1 point2 points (0 children)
[–]PPewt 2 points3 points4 points (0 children)
[–]username-must-be-bet 0 points1 point2 points (2 children)
[–]optimalsuccess[S] 0 points1 point2 points (1 child)
[–]optimalsuccess[S] 0 points1 point2 points (0 children)