Element equals its index
Instructions
Given a sorted array of distinct integers, write a function index_equals_value that returns the lowest index for which array[index] == index.
Return -1 if there is no such index.Your algorithm should be very performant.[input] array of integers ( with 0-based nonnegative indexing )
[output] integerExamples:
Examples:
input: [-8,0,2,5]
output: 2 # since array[2] == 2
input: [-1,0,3,6]
output: -1 # since no index in array satisfies array[index] == index
Random Tests Constraints:
Array length: 200 000
Amount of tests: 1 000
Time limit: 1.5 s
我的代码
我是采用了二分法查找来解决这道题目的,然后我看了以下大多数的解法都是用了二分法,当然我的方法并不是最简单的。
def index_equals_value(arr):
beg=0
end=len(arr)
ls=[]
if arr[0]==0:
return 0
if arr[0]>0:
return -1
while end-beg>1:
mid=(beg+end)//2
if arr[mid]==mid:
ls.append(mid)
end=mid
elif arr[mid]>mid:
end=mid
elif arr[mid]<mid:
beg=mid
return min(ls) if len(ls)>0 else -1