题目
给定两个数组,编写一个函数来计算它们的交集。
难度:简单
示例
输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2]
输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[9,4]
说明:
输出结果中的每个元素一定是唯一的。
我们可以不考虑输出结果的顺序。
解题思路
首先,判断两数组是否为空,空直接返回
第一,申请要返回的数组,首先知道,题目要求数组交集,若存在最大交集,那返回数组就是是两个原数组中长度短的那个数组本身。所以申请返回数组的空间就按照短的原数组长度申请。
第二,将两数组排序,目的是方便之后的依次比较。
第三,依次比较,若数据相等,则存到要返回的数组中,不相等再往后走,再比较。
第第四,在循环结束后,利用realloc()重新把数组长度申请一遍。
C语言代码
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int mycmp(const void* p1, const void* p2)
{
const int* a1 = (const int*)p1;
const int* a2 = (const int*)p2;
return (*a1 > *a2) - (*a1 < *a2);
}
int* intersection(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize)
{
//判空
if (nums1 == NULL || nums2 == NULL)
{
*returnSize = 0;
return NULL;
}
//申请新数组
int ansSize = (nums1Size < nums2Size) ? nums1Size : nums2Size;
int* ans = (int*)malloc(sizeof(int) * ansSize);
if (ans == NULL)
{
return NULL;
}
//将两个原数组排序
qsort(nums1, nums1Size, sizeof(int), mycmp);
qsort(nums2, nums2Size, sizeof(int), mycmp);
int count = 0;
for (int i = 0, j = 0; i < nums1Size && j < nums2Size;)
{
if (nums1[i] < nums2[j])
++i;
else if (nums1[i] > nums2[j])
{
++j;
}
else
{
ans[count++] = nums1[i];
++i;
++j;
//去掉重复项
if (count > 1 && ans[count - 1] == ans[count - 2])
--count;
}
}
//重新申请数组空间
ans = (int*)realloc(ans, sizeof(int) * count);
*returnSize = count;
return ans;
}