Brute force:
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
Runtime: 3584 ms, faster than 14.38% of Python online submissions for Two Sum.
Memory Usage: 14.5 MB, less than 14.64% of Python online submissions for Two Sum.
Two-pass Hash Table:
nums_hash = {}
for index, num in enumerate(nums):
nums_hash[num] = index
for index, num in enumerate(nums):
comp = target - num
if comp in nums_hash.keys() and index != nums_hash[comp]:
return [index, nums_hash[comp]]
Runtime: 1348 ms, faster than 24.52% of Python online submissions for Two Sum.
Memory Usage: 14.2 MB, less than 46.97% of Python online submissions for Two Sum.
One-pass Hash Table:
nums_hash = {}
for index, num in enumerate(nums):
comp = target - num
if comp in nums_hash.keys() and index != nums_hash[comp]:
return [index, nums_hash[comp]]
else:
nums_hash[num] = index
Runtime: 680 ms, faster than 27.87% of Python online submissions for Two Sum.
Memory Usage: 14.3 MB, less than 46.97% of Python online submissions for Two Sum.
Top comments (0)