LeetCode: Intersection of Two Arrays in C

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int compare(const void * a, const void * b) {
   return ( *(int*)a - *(int*)b );
}

int * intersect(int * nums1, int nums1Size, int * nums2, int nums2Size, int * returnSize) {
  int *arr = (int*)malloc(sizeof(int)*nums1Size);
  qsort(nums1, nums1Size, sizeof(int), compare);
  qsort(nums2, nums2Size, sizeof(int), compare);
  
  int i = 0, j = 0, k=0;
    while (i < nums1Size && j < nums2Size) {
        if (nums1[i] < nums2[j])
            i++;
        else if (nums2[j] < nums1[i])
            j++;
        else /* if nums1[i] == nums2[j] */
        {
            arr[k] = nums2[j];
            k++;
            printf(" %d ", nums2[j]);
            j++;
            i++;
        }
    }
    *returnSize = k;
    return arr;
    
}

Leave a Comment