349. Intersection of Two Arrays

刺骨的言语ヽ痛彻心扉 2022-04-25 03:22 213阅读 0赞

Given two arrays, write a function to compute their intersection.

Example 1:

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

Example 2:

  1. Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
  2. Output: [9,4]

Note:

  • Each element in the result must be unique.
  • The result can be in any order.

解题思路:思路一,python的集合有一个求交集的方法

  1. 思路二,将两个数组按照从小到大排序,然后遍历,挨个比较,一样的情况下,再判断是否在新数组,不在的情况下加入到新数组;

python代码:

  1. class Solution:
  2. def intersection(self, nums1, nums2):
  3. """
  4. :type nums1: List[int]
  5. :type nums2: List[int]
  6. :rtype: List[int]
  7. """
  8. l1 = len(nums1)
  9. l2 = len(nums2)
  10. res = set()
  11. if l1 <= l2:
  12. s = nums1
  13. l = nums2
  14. else:
  15. l = nums1
  16. s = nums2
  17. for i in l:
  18. if i in s:
  19. res.add(i)
  20. return list(res)

C语言代码:

  1. /**
  2. * Return an array of size *returnSize.
  3. * Note: The returned array must be malloced, assume caller calls free().
  4. */
  5. int* intersection(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize) {
  6. int i,j,k=0,flag=0;
  7. int lens=nums1Size>nums2Size?nums1Size:nums2Size;
  8. int* re =(int*)malloc(sizeof(int)*lens);
  9. if(nums1Size==0) { * returnSize=k; return nums1; }
  10. if(nums2Size==0) { * returnSize=k; return nums2; }
  11. for(i=0;i<nums1Size;i++)
  12. {//flag用来标识数组re中是否已经存在nums1和nums2的交集,flag==0,则只要比较nums2[j]==nums1[i]
  13. if(flag==0)
  14. for(j=0;j<nums2Size;j++)
  15. { if(nums2[j]==nums1[i])
  16. {flag=1;re[k++]=nums1[i];break;}
  17. }
  18. //flag==1说明re中已存在交集数字,则nums1[i]还需要与re数组中的每个元素进行比较,保证输出结果中的每个元素一定是唯一的
  19. else if(flag==1)
  20. {int t,f=0;
  21. for (t=0;t<k;t++)
  22. if(nums1[i]==re[t]) { f=1;break;}
  23. if(f==1) continue;//一开始写成了break
  24. for(j=0;j<nums2Size;j++)
  25. {
  26. if(nums2[j]==nums1[i])
  27. { flag=1;re[k++]=nums1[i];break;}
  28. }
  29. }
  30. }
  31. * returnSize=k;
  32. return re;
  33. }

发表评论

表情:
评论列表 (有 0 条评论,213人围观)

还没有评论,来说两句吧...

相关阅读