[leetcode]-349. Intersection of Two Arrays(C语言)

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* intersection(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize) {
    int i,j,k,s;
    *returnSize=0;
    int *res;
    res=(int *)calloc(nums1Size,sizeof(int *));
    for(i=0;i<nums1Size;i++)
    {
        for(j=0;j<nums2Size;j++)
        {
            if(nums1[i]==nums2[j])
            {
                for(k=0;k<*returnSize;k++)
                {
                    if(nums1[i]==res[k])
                        break;
                }
                if(k==*returnSize)
                {
                    (*returnSize)++;
                    res[*returnSize-1]=nums1[i];
                }  
            }
        }
    }
    return res;
}

猜你喜欢

转载自blog.csdn.net/shen_zhu/article/details/79575523