Arrays
Arrays
Two Sums
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
complement_index = {}
for i, n in enumerate(nums):
print(i, n)
complement = target - n
print(complement)
complement_index[complement] = i
for i, n in enumerate(nums):
if n in complement_index and i != complement_index[n]:
print(n)
return [i, complement_index[n]]
- Key insight: Figure out the complement for each value in nums, and then store that complement in a dictionary, wit the index of that value. After, iterate through nums again and see if n is in our complement_index dict (which means we found a complement). If so, return our current index of the complement, plus the index of the original value from our first scan. Make sure that both of these indexes aren't the same value.