Skip to content

Instantly share code, notes, and snippets.

@ak9999
Created May 12, 2021 23:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ak9999/a1cbbdb8dd319a9df83d9b82bf4dd2ad to your computer and use it in GitHub Desktop.
Save ak9999/a1cbbdb8dd319a9df83d9b82bf4dd2ad to your computer and use it in GitHub Desktop.
Two Sum Problem Solution
from typing import List
class Solution:
def binary_search(self, container: List[int], key):
low = 0
high = len(container) - 1
while (low <= high):
middle = (low + high) >> 1
middle_value = container[middle]
if middle_value < key:
low = middle + 1
elif middle_value > key:
high = middle - 1
else:
return middle
return None
def twoSum(self, nums: List[int], target: int) -> List[int]:
# Binary Search solution
for index, value in enumerate(nums):
complement = target - value
complement_index = self.binary_search(nums, complement)
if complement_index is not None:
if complement_index != index:
return [index, complement_index]
return None
def two_sum_hash_table(self, nums: List[int], target: int) -> List[int]:
table = dict()
for index, value in enumerate(nums):
complement = target - value
if value not in table:
table[complement] = index
else:
return [index, table[value]]
return []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment