Missing numbers in 53-2-0~n-1-python

Problem: All numbers in an increasing sorted array of length n-1 are unique, and each number is in the range of 0~n-1. There is only one number among n numbers in the range 0~n-1 that is not in the array. Please find this number.

def get_missing_num(nums):
    if len(nums)<1:
        return -1
    begin,end = 0,len(nums)-1
    while begin<end:
        mid = (begin+end)//2
        if nums[mid] == mid:
            begin = mid
        else:
            end = mid
        if begin+1==end:
            break
    if nums[begin]+1==nums[end]:
        return 0
    else:
        return nums[begin]+1

  Note: Use binary search. If the number in the middle is the same as the index, it means the missing number is on the right, let begin point to this position; if the number in the middle is not the same as the index, it means the missing number is on the left, let end point to this position . Finally, two numbers adjacent to begin and end are found. If the two numbers are also different by 1, it means that the first digit of the missing digit is 0, otherwise, the missing number is the middle digit of the two numbers.

Guess you like

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