Intersection of Two Arrays II (C)


  • 0
    P
    int* intersect(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize) {
       int TmpSize=0;
       int *pTemp;
       //Configure Array1 be the shorter one
       if(nums1Size > nums2Size){
           pTemp = nums1;
           TmpSize = nums1Size;
           nums1 = nums2;
           nums1Size = nums2Size;
           nums2 = pTemp;
           nums2Size = TmpSize;
       }
       int **ppRetArray = (int**)malloc(sizeof(int*));
       int k=0;
       for(int i=0; i<nums1Size; i++){
           for(int j=0; j<nums2Size; j++){
               if(nums1[i] == nums2[j]){
                   if (k == 0){
                       //Store address of array element
                       ppRetArray[k] = &nums2[j];
                       k++;
                       break;
                   }
                   else if(k > 0){
                       int nExist = 0;   //1: Exist  0: Not exist
                       //Searching the specific address was stored or not
                       for(int m=0; m<k; m++)
                           if(ppRetArray[m] == &nums2[j]){
                               nExist = 1;
                               break;
                           }             
                       if(nExist==0){
                          ppRetArray = (int**)realloc(ppRetArray, (k+1)*sizeof(int*));
                          ppRetArray[k] = &nums2[j];
                          k++;
                          break;
                       }
                   }//else if
              }//if(nums1[i] == nums2[j])
           }//for
       }//for
      *returnSize = k;
       int *pRetArray = malloc(k*sizeof(int));
       for(int i=0; i<k; i++)
           pRetArray[i] = **(ppRetArray+i);
       return pRetArray;
    

    }


Log in to reply
 

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