Skip to content

Instantly share code, notes, and snippets.

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

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

Select an option

Save tech-cow/4764bdf9ee94b81da964f63f946a2748 to your computer and use it in GitHub Desktop.
def find_first_occ_gd(arr , target):
l , r = 0, len(arr) - 1
while l + 1 < r:
mid = l + (r - l) // 2
if arr[mid] == target:
r = mid
elif arr[mid] < target:
l = mid + 1 #可以不加1,不影响当arr[mid] == target的时候 r = mid的设置
else:
r = mid - 1 #可以不减1,不影响当arr[mid] == target的时候 r = mid的设置
# post
if arr[l] == target: return l
if arr[r] == target: return r
return -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment