C ,my solution, not addtional memory.


  • 0
    D
    int* findDisappearedNumbers(int* nums, int numsSize, int* returnSize) {
        
        int count = 0;
    
        //main part    
        for(int i = 0;i < numsSize; i++){
            if(nums[i] == i+1)  continue;
            int temp = nums[i] - 1;
            while(nums[temp] != nums[i]){
                nums[i] = nums[temp];
                nums[temp] = temp + 1;
                if(nums[i] != i+1) temp = nums[i] - 1;
                else break;
            }
        }
    
    // in another type, I use -1 to indicated the pos is ok,so I can get the count, but the source array will be changged.
    // this solution will not change the source array, but one more loop.
        for(int j = 0; j < numsSize; j++){
            if(nums[j] != j + 1)
                count++;
        }
        *returnSize = count;
        int* answer = (int*) malloc(sizeof(int) * count);
        count = 0;
        for(int j = 0; j< numsSize; j++){
            if(nums[j] != j + 1){
                answer[count++] = j + 1;
            }
        }
        return answer;
    }
    

Log in to reply
 

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