Least index matches its value
Binary search:
有兩種寫法, <=和< ,l永遠都是mid+1,只有r會不一樣
"""
Given a sorted array arr of distinct integers,
write a function indexEqualsValueSearch that returns the lowest index i for which arr[i] == i.
Return -1 if there is no such index. Analyze the time and space complexities of your solution and explain its correctness.
"""
def indexEqualsValueSearch(arr):
l = 0
r = len(arr) - 1
while l <= r:
mid = l + (r-l)/2
if mid > arr[mid]:
l = mid + 1
elif mid < arr[mid]:
r = mid - 1
else:
if mid and arr[mid-1] == mid - 1:
r = mid - 1
else:
return mid
return -1
arr = [-9,0,2,5]
print indexEqualsValueSearch(arr)