当前位置:网站首页>349. intersection of two arrays

349. intersection of two arrays

2022-06-09 10:08:00 Mr Gao

349. Intersection of two arrays

Given two arrays nums1 and nums2 , return Their intersection . Every element in the output must be only Of . We can Regardless of the order of the output results .

Example 1:

Input :nums1 = [1,2,2,1], nums2 = [2,2]
Output :[2]

Example 2:

Input :nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output :[9,4]
explain :[4,9] It is also passable

This question is actually quite simple , We can solve the problem by setting up an auxiliary array :
The solution code is as follows :

/** * Note: The returned array must be malloced, assume caller calls free(). */
int* intersection(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize){
    
   int* a=(int* )malloc(sizeof(int)*1000);
      int* b=(int* )malloc(sizeof(int)*1000);
   int i=0;
   for(i=0;i<1000;i++){
    
       a[i]=0;
   }
     for(i=0;i<nums1Size;i++){
    
       if(a[nums1[i]]==0){
    
           a[nums1[i]]=1;
       }
   }
   int p=0;
     for(i=0;i<nums2Size;i++){
    
       if(a[nums2[i]]==1){
    
           a[nums2[i]]++;
           b[p++]=nums2[i];
       }
   }
   *returnSize=p;
   return b;

}
原网站

版权声明
本文为[Mr Gao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206090927456456.html