268 Missing Number

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
For example,

Given nums = [0, 1, 3] return 2.
  • Note: Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
class Solution {
public:
    int missingNumber(vector<int>& nums) {
        int n = nums.size();
        int j, tmp, tmp1;
        for ( int i = 0; i <= n-1; i++ ) {
            j = i;
            tmp = nums[j];
            while ( true ) {
                if ( tmp >= n ) break;
                if ( nums[tmp] == tmp ) break;
                tmp1 = nums[tmp];
                nums[tmp] = tmp;
                tmp = tmp1;
            }
        }
        for ( int i = 0; i <= n-1; i++ ) {
            if ( nums[i] != i ) return i;
        }
        return n;
    }
};

Bit Manipulation Solution:

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

results matching ""

    No results matching ""