C语言初阶力扣刷题——349. 两个数组的交集【难度:简单】

1. 题目描述

力扣在线OJ题目

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

示例:

输入:nums1 = [1,2,2,1], nums2 = [2,2]

输出:[2]

输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]

输出:[9,4]

2. 思路

直接暴力求解。将 nums1 数组中的每一个数字,判断是否存在于 nums2 数组中,通过这种方式找出交集数据,找出之后判断这个数组是否已经在返回数组中存在,不存在则添加到返回数组中即可。

3. 代码实现

c 复制代码
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* intersection(int* nums1, int nums1Size, int* nums2, int nums2Size,
                  int* returnSize) {
    static int arr[1000];
    *returnSize = 0;
    int i, j, k;
    for (i = 0; i < nums1Size; i++) {
        for (j = 0; j < nums2Size; j++) {
            if (nums2[j] == nums1[i])
                break; // 判断nums1[i] 是否在nums2数组中
        }
        if (j == nums2Size) { // nums1中i位置的数据在nums2数组中不存在,则非交集数据
            continue;
        }
        // 只有在另一个数组中存在的数据才能走下来,判断是否已经被添加到返回数组中
        for (j = 0; j < *returnSize; j++) {
            if (nums1[i] == arr[j])
                break; // 判断nums1[i] 是否在 arr 这个返回数组中
        }
        if (j == *returnSize) { // 不在返回数组中,则添加到返回数组中
            arr[*returnSize] = nums1[i];
            *returnSize += 1;
        }
    }
    return arr;
}
相关推荐
大尚来也1 分钟前
PHP 反序列化漏洞深度解析:从原理利用到 allowed_classes 防御实战
android·开发语言·php
雕刻刀4 分钟前
ERROR: Failed to build ‘natten‘ when getting requirements to build wheel
开发语言·python
qq_416018724 分钟前
高性能密码学库
开发语言·c++·算法
小碗羊肉13 分钟前
【从零开始学Java | 第十八篇】BigInteger
java·开发语言·新手入门
宵时待雨16 分钟前
C++笔记归纳14:AVL树
开发语言·数据结构·c++·笔记·算法
执笔画流年呀30 分钟前
PriorityQueue(堆)续集
java·开发语言
爱编码的小八嘎30 分钟前
C语言完美演绎5-3
c语言
山川行33 分钟前
关于《项目C语言》专栏的总结
c语言·开发语言·数据结构·vscode·python·算法·visual studio code
呜喵王阿尔萨斯35 分钟前
C and C++ code
c语言·开发语言·c++
星辰徐哥38 分钟前
C语言游戏开发:Pygame、SDL、OpenGL深度解析
c语言·python·pygame