C fast (40ms) & clean solution with precision space allocation


  • 0
    Y
    /**
     * Return an array of size *returnSize.
     * Note: The returned array must be malloced, assume caller calls free().
     */
    int* findDisappearedNumbers(int* nums, int numsSize, int* returnSize) {
        int i = 0;
        *returnSize = numsSize;
        for (int i = 0; i < numsSize; i++) {
            int index = abs(nums[i]) - 1;
            if (nums[index] < 0) continue;
            nums[index] *= -1;
            (*returnSize) -= 1; 
        }
        int * tarArr = (int *) calloc(*returnSize, sizeof(int));
        // cdex is to fix the corrupted memory layout in leetcode 
        // while using malloc/calloc 
        int cdex = 0;
        for (i = 0; i < numsSize; i++) {
            if (nums[i] > 0) {
                tarArr[cdex] = (i + 1);
                cdex++;
            }
        }
        return tarArr;
    }
    

Log in to reply
 

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