Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Note:
Each element in the result must be unique.
The result can be in any order.
/**
* Return an array of size *returnSize.
* 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* intersection(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize)
{
if(NULL == nums1 || NULL==nums2)
return NULL;
int cnt = 0;
*returnSize =(nums1Size > nums2Size) ? nums2Size:nums1Size;
int *res =(int *)malloc(*returnSize * sizeof(int));
/*sort nums1 nums2*/
qsort (nums1, nums1Size, sizeof(int), compare);
qsort (nums2, nums2Size, sizeof(int), compare);
for(int i = 0;i < nums1Size;i++ )
{
/*nums1 element found in nums2*/
if(bsearch (&nums1[i], nums2, nums2Size, sizeof (int), compare) != NULL)
{
/*common element is not in res,add it,the res length is cnt*/
if(NULL == bsearch (&nums1[i], res, cnt, sizeof (int), compare))
res[cnt++] = nums1[i];
}
}
*returnSize = cnt;
return res;
}