找到两个数组中的公共元素

class Solution(object):
    def findIntersectionValues(self, nums1, nums2):

        set_nums2 = set(nums2)
        count1 = sum(1 for num in nums1 if num in set_nums2)

        set_nums1 = set(nums1)
        count2 = sum(1 for num in nums2 if num in set_nums1)

        return [count1, count2]
class Solution {
    public int[] findIntersectionValues(int[] nums1, int[] nums2) {
        HashSet<Integer> setNums2 = new HashSet<>();
        for (int num : nums2) {
            setNums2.add(num);
        }
        
        // 统计 nums1 中满足条件的下标数量
        int count1 = 0;
        for (int num : nums1) {
            if (setNums2.contains(num)) {
                count1++;
            }
        }
        
        // 将 nums1 转换为集合
        HashSet<Integer> setNums1 = new HashSet<>();
        for (int num : nums1) {
            setNums1.add(num);
        }
        
        // 统计 nums2 中满足条件的下标数量
        int count2 = 0;
        for (int num : nums2) {
            if (setNums1.contains(num)) {
                count2++;
            }
        }
        
        return new int[]{count1, count2};

    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用两个循环来遍历这两个数组,对于每一个数组中元素,再用一个循环遍历另一个数组,如果找到了相同的元素,则将其加入到公共元素数组中,并从原数组中删除该元素,以免重复加入。 以下是一个示例代码,其中common1和common2分别为两个数组中公共元素: ```c #include <stdio.h> void findCommon(int arr1[], int arr2[], int len1, int len2, int common1[], int common2[], int *lenCommon1, int *lenCommon2) { int i, j, k; *lenCommon1 = 0; *lenCommon2 = 0; // 遍历数组1 for (i = 0; i < len1; i++) { // 遍历数组2 for (j = 0; j < len2; j++) { // 如果找到相同的元素 if (arr1[i] == arr2[j]) { // 将其加入到公共元素数组中 common1[*lenCommon1] = arr1[i]; (*lenCommon1)++; // 从数组2中删除该元素 for (k = j; k < len2 - 1; k++) { arr2[k] = arr2[k+1]; } len2--; // 退出内层循环 break; } } } // 遍历数组2 for (i = 0; i < len2; i++) { // 遍历数组1(已经从数组2中删除了元素,所以不会重复加入到公共元素数组) for (j = 0; j < len1; j++) { // 如果找到相同的元素 if (arr2[i] == arr1[j]) { // 将其加入到公共元素数组中 common2[*lenCommon2] = arr2[i]; (*lenCommon2)++; // 退出内层循环 break; } } } } int main() { int arr1[] = {1, 2, 3, 4, 5}; int arr2[] = {2, 4, 6, 8, 10}; int len1 = sizeof(arr1) / sizeof(arr1[0]); int len2 = sizeof(arr2) / sizeof(arr2[0]); int common1[5], common2[5], lenCommon1, lenCommon2; findCommon(arr1, arr2, len1, len2, common1, common2, &lenCommon1, &lenCommon2); printf("Common elements in arr1 and arr2:\n"); for (int i = 0; i < lenCommon1; i++) { printf("%d ", common1[i]); } printf("\nCommon elements in arr2 and arr1:\n"); for (int i = 0; i < lenCommon2; i++) { printf("%d ", common2[i]); } return 0; } ``` 注意,这个算法的时间复杂度为 O(len1 * len2),如果数组比较大,可能会比较耗时。可以考虑使用哈希表等数据结构来优化算法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值