From 3f7dd67a8031663d2b673a41587e3a640e0a4b1f Mon Sep 17 00:00:00 2001 From: FrankLin Date: Fri, 1 Apr 2022 10:57:25 -0400 Subject: [PATCH] Add C version for LeetCode349 using array --- problems/0349.两个数组的交集.md | 32 ++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/problems/0349.两个数组的交集.md b/problems/0349.两个数组的交集.md index 82be1829..64d80a37 100644 --- a/problems/0349.两个数组的交集.md +++ b/problems/0349.两个数组的交集.md @@ -281,6 +281,38 @@ impl Solution { } } ``` + +C: +```C +int* intersection1(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize){ + + int nums1Cnt[1000] = {0}; + int lessSize = nums1Size < nums2Size ? nums1Size : nums2Size; + int * result = (int *) calloc(lessSize, sizeof(int)); + int resultIndex = 0; + int* tempNums; + + int i; + + //Calculate the number's counts for nums1 array + for(i = 0; i < nums1Size; i ++) { + nums1Cnt[nums1[i]]++; + } + + //Check if the value existing in nums1 count array + for(i = 0; i < nums2Size; i ++) { + if(nums1Cnt[nums2[i]] > 0) { + result[resultIndex] = nums2[i]; + resultIndex ++; + //Clear this count to avoid duplicated value + nums1Cnt[nums2[i]] = 0; + } + } + * returnSize = resultIndex; + return result; +} +``` + ## 相关题目 * 350.两个数组的交集 II