0~n-1中缺失的数字(二分查找法)

题目描述
一个长度为n-1的递增排序数组中的所有数字都是唯一的,并且每个数字都在范围0~n-1之内。这n个数字中,有且只有一个数字不在该数组中,请找出数字
排序数组,用二分查找法
如果不相等,前面的数字相等,返回
否则,继续向前遍历

class Solution:
    def findMissNum(self, numbers):
        length = len(numbers)
        if numbers == []:
            return -1
        left = 0
        right = length - 1
        while(left <= right):
            middle = (left + right) >> 1
            if numbers[middle] != middle:
                if middle == 0 or (middle > 0 and numbers[middle - 1] == middle - 1):
                    return middle
                else:
                    right = middle - 1
            else:
                left = middle + 1
        if left == length:
            return length
        return -1
numbers = [0,1,2,3,4,5,6,7]
print(Solution().findMissNum(numbers))

你可能感兴趣的:(基础算法,paper)