Skip to content

[LeetCode] 349. Intersection of Two Arrays #12

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Animenzzzz opened this issue Jul 28, 2019 · 0 comments
Open

[LeetCode] 349. Intersection of Two Arrays #12

Animenzzzz opened this issue Jul 28, 2019 · 0 comments

Comments

@Animenzzzz
Copy link
Owner

题目描述:

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

示例 1:

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

示例 2:

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

说明:

输出结果中的每个元素一定是唯一的。
我们可以不考虑输出结果的顺序。

解题思路:这题比较简单,两个数组嵌套遍历,第三层遍历是过滤掉会重复的值。有看网上的方法,大部分都是先排序。

C解题:

int* intersection(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize){
    *returnSize = 0;
    int *result = (int *)malloc(nums1Size * sizeof(int *));
    for (int i = 0; i < nums1Size; i++)
    {
        for (int j = 0; j < nums2Size; j++)
        {
            if (nums1[i] == nums2[j])
            {
                int flag = 0;
                for (int k = 0; k < (*returnSize); k++)
                {
                    if (result[k] == nums1[i]) flag = 1;
                }
                if (!flag){
                    result[*returnSize] = nums1[i];
                    (*returnSize)++;
                }
                
            }
            
        }
        
    }
    return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant