[tag] hash table, two pointers
- use a hash table, key: num, value: index.
- need to first look up on the dict then add number to avoid case of 4 + 4 = 8.
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
num_dict = defaultdict(int)
ans = []
for i in range(len(nums)):
nums_to_find = target - nums[i]
if nums_to_find in num_dict:
return [i, num_dict[nums_to_find]]
else:
num_dict[nums[i]] = i
return [-1, -1]