剑指 Offer 53 - II. 0~n-1中缺失的数字

//二分查找法
class Solution {
    public int missingNumber(int[] nums) {
        if(nums == null || nums.length <= 0) return -1;
        //定义左右边界
        int left = 0;
        int right = nums.length -1;
        
        while(right >= left){
            int mid = (left + right)/2;
            if(nums[mid] != mid){// 在左区间 【left,mid - 1】
                
                if( mid == 0 || nums[mid-1] == mid-1){
                    return mid;
                }
                right = mid -1;
            }else { // 在 右区间 【mid+1 ,right】
                left = mid+1;
            }
        }
        if(left == nums.length)
        return nums.length;
        return -1;
    }
    
}

 

posted @ 2020-12-17 01:45  peanut_zh  阅读(67)  评论(0编辑  收藏  举报