The missing number in 0~n-1-2

Likou Address

There is a problem with the title description, each number is in the range of 0~n instead of 0~n-1

Traverse:

Missing middle part

class Solution {
public:
    int missingNumber(vector<int>& nums) {
        int len = nums.size();
        if (nums[0] != 0) return 0;
        if (nums[len - 1] != len) return len;
        
        int record = nums[0];
        for (int i = 0; i < len; ++i) {
            if (nums[i] - record > 1) return record + 1;
            record = nums[i];
        }
        return -1;
    }
};

Two points:

Considering the fact that there is only one number in the array, the while loop should add an equal sign. Because of the equal sign, when finally exiting the loop, low must be greater than high. According to the condition, the value of low is the target number.

class Solution {
public:
    int missingNumber(vector<int>& nums) {
        int len = nums.size();
        int low = 0, high = len - 1;
        while (low <= high) {
            int mid = (low + high) >> 1;
            if (nums[mid] == mid) {
                low = mid + 1;
            }
            else {
                high = mid - 1;
            }
        }
        return low;
    }
};

XOR:

class Solution {
public:
    int missingNumber(vector<int>& nums) {
        int len = nums.size();
        int res = len;
        for (int i = 0; i < len; ++i) {
            res ^= nums[i] ^ i;
        }
        return res;
    }
};

 

Guess you like

Origin blog.csdn.net/TESE_yan/article/details/114222226