subject : Suppose a Monotone increasing Each element in the array of is an integer and unique . Please program a function to find any element in the array whose value is equal to its subscript . for example , In the array [-3, -1, 1, 3, 5] in , Numbers 3 Equal to its subscript .
Input :[-3, -1, 1, 3, 5]
Output :3
Be careful : If it doesn't exist , Then return to -1.
Ideas : Two points
Code :
class Solution:
def func(self , nums):
if len(nums) == 0:
return -1
lo , hi = 0 , len(nums)-1
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] < mid:
lo = mid + 1
elif nums[mid] > mid:
hi = mid -1
else:
return mid
return -1
a = [-3, -1, 1, 3, 5]
s = Solution()
print(s.func(a))