Whats wrong in this code?


  • 1
    S
      int* twoSum(int* nums, int numsSize, int target) {
     int i,j;
     int* r;
     r=(int *)malloc(2*sizeof(int));
     nums=(int *)malloc(numsSize*sizeof(int)); 
     for(i=0;i<numsSize;i++)
      {
       for(j=i+1;j<numsSize;j++)
       if(*(nums+i)+*(nums+j)==target)
       { *r=i+1;
         *(r+1)=j+1;
        return(r);
         }
      }
    r[0]=r[1]=0;
    return(r);
    

    }


  • 1
    V

    Please paste your code in proper format. Others skip it or else


  • 0
    S

    converted into proper format


  • 0
    V

    The problem is in:

    nums=(int )malloc(numsSizesizeof(int));

    Why are you allocating space to 'nums' which was already passed to this function.

    Remove this line, it will pass


  • 0
    S

    still not accepted. Time limit exceeded.


  • 0
    V

    TLE is because your algorithm is not the optimized one. Your logic is taking O(n^2) complexity, For larger n this might exceeding the stipulated time limit LC has set.

    Try to think about how to optimize the algorithm.


Log in to reply
 

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