From intuitive to best in C, well-commented


  • 0
    //AC - 12ms - using O(n) space;
    //using boolean array to indicate its existence;
    int missingNumber(int* nums, int size)
    {
        bool *arr = (int*)malloc(sizeof(bool)*(size+1));
        memset(arr, 0, sizeof(bool)*(size+1));
        for(int i = 0; i < size; i++)
            arr[nums[i]] = true;
        for(int i = 0; i <= size; i++)
            if(!arr[i])
                return i;
    }
    

    //AC - 16ms - using O(1) space and O(n) time;
    //since all elements are distinct and range from 1 to size;
    //so the missing one will be replaced by zero, so math can handle it;
    int missingNumber(int* nums, int size)
    {
        int sum = (size*(size+1))/2;
        int t = 0;
        for(int i = 0; i < size; i++) t += nums[i];
        return sum-t;
    }
    

    //AC - 12ms - using O(1) space and O(n) time;;
    //xor always can surprise us considering a^a=0 and 0^b=b;
    int missingNumber(int* nums, int size)
    {
        int t = size;
        for(int i = 0; i < size; i++)
            t ^= nums[i]^i;
        return t;
    }

Log in to reply
 

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