LeetCode 349. 两个数组的交集

题目

给定两个数组,编写一个函数来计算它们的交集。

难度:简单

示例

输入: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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_索伦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值