[LeetCode]349. Intersection of Two Arrays ★

每天一道编程题

  • 题目描述
  • 样例
  • python解法
  • C语言解法

题目描述

Given two arrays, write a function to compute their intersection.
题目大意:求两个给定集合的交集

样例

Example 1:

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

Example 2:

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

python解法

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        set1 = set(nums1)
        set2 = set(nums2)
        s = set1.intersection(set2)
        return list(s)

Runtime: 52 ms, faster than 84.32% of Python3 online submissions for Intersection of Two Arrays.
Memory Usage: 14 MB, less than 5.88% of Python3 online submissions for Intersection of Two Arrays.
题后反思:无

C语言解法

struct linklist{
    int val;
    struct linklist *next;
};

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */

int location(int *num, int len, int com)
{
    for (int i=0;i<len;i++)
    {
        if (num[i] == com)
            return i;
    }
    return -1;
}

int* intersection(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize){
    if (!nums1Size || !nums2Size)
    {
        *returnSize=0;
        return NULL;
    }
    struct linklist *num[nums2Size];
    for(int i=0;i<nums2Size;i++)
        num[i] = NULL;
    int remain = 0;
    struct linklist *link = NULL;
    for(int i=0;i<nums2Size;i++)
    {
        remain = nums2[i]%nums2Size;
        link = (struct linklist *)malloc(sizeof(struct linklist));
        link -> val = nums2[i];
        link -> next = num[remain];
        num[remain] = link;
    }
    int *returnValue = NULL;
    *returnSize = 0;
    for (int i=0;i<nums1Size;i++)
    {
        remain = nums1[i]%nums2Size;
        link = num[remain];
        while(link)
        {
            if(link -> val == nums1[i])
            {
                if (location(returnValue, *returnSize, nums1[i]) == -1)
                {
                    returnValue = (struct linklist*)realloc(returnValue, sizeof(int)*(*returnSize + 1));
                    returnValue[*returnSize] = nums1[i];
                    (*returnSize) ++;
                    break;
                }
            }
            link = link->next;
        }
    }
    return returnValue;
}

Runtime: 4 ms, faster than 94.02% of C online submissions for Intersection of Two Arrays.
Memory Usage: 8.8 MB, less than 100.00% of C online submissions for Intersection of Two Arrays.
题后反思:

  1. 使用了哈希表来解决数组查找慢的问题。
  2. C语言中没有相应的数据结构,自己实现的代码明显多很多。

文中都是我个人的理解,如有错误的地方欢迎下方评论告诉我,我及时更正,大家共同进步

你可能感兴趣的:(LeetCode)