C++ simple solution in O(n)

  • 0

    if we add 0,1,...,n to this array, then every number in this array appears twice except one, which is the number we are looking for.

    so we just need to do exclusive on all numbers and 0,1,..,n.

    int missingNumber(vector<int>& nums) {
        int n = nums.size(), r = n;
        for(int i = 0; i < n; i++) {
            r ^= i;
            r ^= nums[i];
        return r;

Log in to reply

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