53-3-Elements with equal values and subscripts in an array-python

Question: Assume that each element in a monotonically increasing array is an integer and is unique. Please find any element in the array whose value is equal to its subscript.

def get_num_same_index(nums):
    if len(nums)<1:
        return -1
    begin,end = 0,len(nums)-1
    while begin<end:
        mid = (begin+end)//2
        if nums[mid] == mid:
            return nums[mid]
        elif nums[mid]<mid:
            begin = mid+1
        elif nums[mid]>mid:
            end = mid-1
    return -1

  Note: Using binary search, when the number in the middle is the same as the index, the return value is ended; when the middle value is less than the index, begin points to the middle value +1; when the middle value is greater than the index, end points to the middle value -1.

Guess you like

Origin blog.csdn.net/wh672843916/article/details/105503751