首页 > 试题广场 >

两个数组的交集

[编程题]两个数组的交集
  • 热度指数:2194 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定两个整数数组分别为nums1, nums2,找到它们的公共元素并按返回。
数据范围:


示例1

输入

[1,2 ],[2,2,2,2]

输出

[2]

说明

两个数组的公共元素只有2 
示例2

输入

[1,2,3],[8,2,2,3,8]

输出

[2,3]

说明

两个数组的公共元素为2和3,返回[3,2]也是一个正确的答案 
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param nums1 int整型一维数组 
 * @param nums1Len int nums1数组长度
 * @param nums2 int整型一维数组 
 * @param nums2Len int nums2数组长度
 * @return int整型一维数组
 * @return int* returnSize 返回数组行数
 */
int* intersection(int* nums1, int nums1Len, int* nums2, int nums2Len, int* returnSize ) {
    // write code here
    int* hash=(int *)calloc(1000,sizeof(int));
    int* ans=(int *)malloc(1000*sizeof(int));
    for(int i=0;i<nums1Len;i++){
        hash[nums1[i]-1]=1;
    }
    int count=0;
    for(int j=0;j<nums2Len;j++){
        if(hash[nums2[j]-1]==1){
            hash[nums2[j]-1]+=1;
            if(hash[nums2[j]-1]==2){
                    ans[count++]=nums2[j];
        }
        }
    }
    *returnSize=count;
    return ans;

    
}

发表于 2022-12-24 07:52:44 回复(0)

问题信息

难度:
1条回答 2707浏览

热门推荐

通过挑战的用户

查看代码