The brute force approach is simple. Loop through each element x and find if there is another value that equals to target - x.
Time complexity: O(n2)
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for x in range(len(nums) - 1):
for y in range(x + 1, len(nums)):
if nums[x] + nums[y] == target:
return x, y
2. Two-pass Hash Table
To improve our run time complexity, we need a more efficient way to check if the complement exists in the array. If the complement exists, we need to look up its index. What is the best way to maintain a mapping of each element in the array to its index? A hash table. We reduce the look up time from O(n) to O(1) by trading space for speed.
A simple implementation uses two iterations. In the first iteration, we add each element's value and its index to the table. Then, in the second iteration we check if each element's complement target - nums[i] exists in the table.
class Solution(object):
def twoSum(self, nums, target):
hashmap={}
for i in range(len(nums)):
hashmap[nums[i]] = i
for i in range(len(nums)):
newnum = target - nums[i]
if hashmap.has_key(newnum) and i != hashmap[newnum]:
return i, hashmap[newnum]
class Solution(object):
def twoSum(self, nums, target):
hashmap = {}
for i in range(len(nums)):
newnum = target - nums[i]
if nums[i] in hashmap:
return hashmap[nums[i]],i
else:
hashmap[newnum] = i