Binary search solution


  • 0
    X
    class Solution {
    public:
        int missingNumber(vector<int>& nums) {
            sort(nums.begin(), nums.end());
            int n=nums.size();
            if(nums[0] == 1) return 0;
            if(nums[n-1] == n-1) return n;
    
            int first=0, last=n-1;
            while(first <= last) {
                int mid = first + (last-first)/2;
                if(nums[mid-1] + 1 != nums[mid]) return nums[mid-1]+1;
                if(mid == nums[mid])
                    first = mid+1;
                else
                    last = mid-1;
            }
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.