Skip to content

Instantly share code, notes, and snippets.

@tech-cow
Created October 16, 2018 19:45
Show Gist options
  • Select an option

  • Save tech-cow/16398bbe75c0e7bf64f9a7afcc33821e to your computer and use it in GitHub Desktop.

Select an option

Save tech-cow/16398bbe75c0e7bf64f9a7afcc33821e to your computer and use it in GitHub Desktop.
def find_nearest(arr, target):
l , r = 0, len(arr) - 1
while l + 1 < r:
if arr[mid] == target:
return mid
elif arr[mid] < target:
l = mid
else:
r = mid
#preprocess
if abs(target - arr[l]) >= abs(target - arr[r]):
return l
else:
return r
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment