ACWING68. The missing numbers 0 to n-1 (to prove safety offer, two points)

All numbers in ascending order of length n-1 in the array are unique, and each number in the range of 0 to n-1.

There is only one number is not in the array, find the number in the range 0 to n-1 n digits in.

Sample
input: [0,1,2,4]

Output: 3

Ideas:
the deletion position and after the portion, satisfy a [i] = i + 1 , the two boundary points can be assigned. Ans-half can not be updated to the time, that is missing is the last number, the answer is returned nums.size (), so ans initialized nums.size ().

class Solution {
public:
    int bin(vector<int>& nums) {
        int l = 0,r = nums.size() - 1;
        int ans = nums.size();
        while(l <= r) {
            int mid = (l + r) >> 1;
            if(nums[mid] > mid) {
                ans = mid;
                r = mid - 1;
            }
            else l = mid + 1;
        }
        return ans;
    }
    
    int getMissingNumber(vector<int>& nums) {
        int n = nums.size();
        if(!n)return 0;
        int ans = bin(nums);
        return ans;
    }
};
Published 843 original articles · won praise 28 · views 40000 +

Guess you like

Origin blog.csdn.net/tomjobs/article/details/104995065