Skip to content

[LeetCode] 350. 两个数组的交集 II #16

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 30, 2019 · 0 comments
Open

[LeetCode] 350. 两个数组的交集 II #16

Animenzzzz opened this issue Jul 30, 2019 · 0 comments

Comments

@Animenzzzz
Copy link
Owner

题目描述:

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

示例 1:

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

示例 2:

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

说明:

输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。
我们可以不考虑输出结果的顺序。

进阶:

如果给定的数组已经排好序呢?你将如何优化你的算法?
如果 nums1 的大小比 nums2 小很多,哪种方法更优?
如果 nums2 的元素存储在磁盘上,磁盘内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办?

解题思路:
这题如果不用C,直接用哈希map就行。主要是这题的整数可能为负,所以用不了map数组解题。不用map的话:先排序,然后找到相等的存入数组就可以了,比较简单

C解题:

int* intersect(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize){
    int map[10000] = {0};
    int *result = (int *)malloc(nums1Size*sizeof(int));
    *returnSize = 0;
    int index = 0;
    for (int i = 0; i < nums1Size; i++)
    {
        for (int j = i+1; j < nums1Size; j++)
        {
            if (nums1[i]>nums1[j])
            {
                int tmp = nums1[i];
                nums1[i] = nums1[j];
                nums1[j] = tmp;
            }
        }
    }
    for (int i = 0; i < nums2Size; i++)
    {
        for (int j = i+1; j < nums2Size; j++)
        {
            if (nums2[i]>nums2[j])
            {
                int tmp = nums2[i];
                nums2[i] = nums2[j];
                nums2[j] = tmp;
            }
        }
    }
    int tmp_index = 0;
    for (int i = 0; i < nums1Size; i++){
        for (int j = tmp_index; j < nums2Size; j++)
        {
            if (nums1[i] == nums2[j])
            {
                result[index] = nums1[i];
                index++;
                (*returnSize)++;
                tmp_index = j+1;
                break;
            }
        }
    }
    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