Skip to content

Instantly share code, notes, and snippets.

@ericness
Created February 12, 2022 22:15
Show Gist options
  • Select an option

  • Save ericness/5a00db56a9d3cc385a8344809851edd6 to your computer and use it in GitHub Desktop.

Select an option

Save ericness/5a00db56a9d3cc385a8344809851edd6 to your computer and use it in GitHub Desktop.
LeetCode 167 binary search attempt 2
from typing import List
class Solution:
"""Solution class for Two Sum"""
def twoSum( # pylint: disable=invalid-name
self, numbers: List[int], target: int
) -> List[int]:
"""Find the indices of the two numbers that add to target.
Args:
numbers (List[int]): Sorted list of ints
target (int): Target to sum to
Returns:
List[int]: List of two indices added by one
"""
for base_index, base_value in enumerate(numbers):
search_index = self.search_value(
numbers[base_index + 1 :], target - base_value
)
if search_index >= 0:
return [base_index + 1, base_index + search_index + 2]
raise ValueError("No solution found")
def search_value(self, numbers: List[int], value: int) -> int:
"""Find the index of `value` in `numbers`. Otherwise
return -1.
Args:
numbers (List[int]): Array of numbers to search
value (int): Value to search for
Returns:
int: Index of value
"""
lower_bound = 0
upper_bound = len(numbers) - 1
while upper_bound >= lower_bound:
midpoint = (upper_bound + lower_bound) // 2
value_at_midpoint = numbers[midpoint]
if value_at_midpoint > value:
upper_bound = midpoint - 1
elif value_at_midpoint < value:
lower_bound = midpoint + 1
else:
return midpoint
return -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment