(1. Two Sum)[https://leetcode.com/problems/two-sum/]
Runtime: Runtime 0ms Beats 100.00% Memory Usage: 19.06 MB Beats 24.63%
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# fill a hash map with a list of indexes where the value appears
# a_map = {}
# for index, val in enumerate(nums):
# if val in a_map:
# a_map[val].append(index)
# else:
# a_map[val] = [index]
# go right to left
# search for target - value where the index is different then the current index
# if exists return
# for index, value in enumerate(nums):
# if target - value in a_map:
# a_list = a_map[target-value]
# for a_list_i in a_list:
# if a_list_i != index:
# return [index, a_list_i]
# this solution can be improved as if we keep the latest occurence of the index we dont need to keep all
# of them, if its the same index them its occurence is unique
# fill a hash map with a list of indexes where the value appears
a_map = {}
for index, val in enumerate(nums):
a_map[val] = index
# go right to left
# search for target - value where the index is different then the current index
# if exists return
# else continue
for index, value in enumerate(nums):
if target - value in a_map:
a_value = a_map[target-value]
if a_value != index:
return [index, a_value]