aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2024-07-01 18:13:47 -0600
committerJack Sangdahl <[email protected]>2024-07-01 18:13:47 -0600
commit1cb433cf3ef98dc8fbd7722a05c09668199d3c26 (patch)
treebab5511469d4de453980f03ddbbb5650a3774b45
parentce20c76c9f401401730320a958f86911c6c1f2c1 (diff)
downloadleetcode-1cb433cf3ef98dc8fbd7722a05c09668199d3c26.tar.gz
leetcode-1cb433cf3ef98dc8fbd7722a05c09668199d3c26.zip
350. intersection of two arrays II
-rw-r--r--intersection_2_array2.c38
-rw-r--r--intersection_2_array2.py32
2 files changed, 70 insertions, 0 deletions
diff --git a/intersection_2_array2.c b/intersection_2_array2.c
new file mode 100644
index 0000000..75c7365
--- /dev/null
+++ b/intersection_2_array2.c
@@ -0,0 +1,38 @@
+// 350. Intersection of Two Arrays II
+#include "leetcode.h"
+
+/*
+ * given two integer arrays 'nums1' and 'nums2' return an array of their
+ * intersection. each element in the result must appear as many times as it
+ * shows in both arrays and you may return the result in any order.
+ */
+
+int *intersect(int *nums1, int nums1Size, int *nums2, int nums2Size,
+ int *returnSize) {
+ int *hash = (int *)malloc(1001 * sizeof(int)),
+ *ans = (int *)malloc(1000 * sizeof(int)), n = 0;
+ for (int i = 0; i < nums1Size; i++)
+ hash[nums1[i]]++;
+ for (int i = 0; i < nums2Size; i++)
+ if (hash[nums2[i]]) {
+ ans[n++] = nums2[i];
+ hash[nums2[i]]--;
+ }
+ *returnSize = n;
+ free(hash);
+ return ans;
+}
+
+int main() {
+ int n11[] = {1, 2, 2, 1}, n21[] = {2, 2}, n12[] = {4, 9, 5},
+ n22[] = {9, 4, 9, 8, 4}, rs1, rs2;
+ int *i1 = intersect(n11, ARRAY_SIZE(n11), n21, ARRAY_SIZE(n21), &rs1);
+ int *i2 = intersect(n12, ARRAY_SIZE(n12), n22, ARRAY_SIZE(n22), &rs2);
+ for (int i = 0; i < rs1; i++)
+ printf("%d ", i1[i]); // expect: 2 2
+ printf("\n");
+ for (int i = 0; i < rs2; i++)
+ printf("%d ", i2[i]); // expect: 4 9
+ printf("\n");
+ free(i1), free(i2);
+}
diff --git a/intersection_2_array2.py b/intersection_2_array2.py
new file mode 100644
index 0000000..2c9889c
--- /dev/null
+++ b/intersection_2_array2.py
@@ -0,0 +1,32 @@
+# 350. Intersection of Two Arrays II
+from collections import Counter
+
+"""
+given two integer arrays 'nums1' and 'nums2' return an array of their
+intersection. each element in the result must appear as many times as it
+shows in both arrays and you may return the result in any order.
+"""
+
+
+class Solution(object):
+ def intersect(self, nums1, nums2):
+ """
+ :type nums1: List[int]
+ :type nums2: List[int]
+ :rtype: List[int]
+ """
+ if len(nums1) > len(nums2):
+ return self.intersect(nums2, nums1)
+ cnt = Counter(nums1)
+ ans = []
+ for i in nums2:
+ if cnt[i] > 0:
+ ans.append(i)
+ cnt[i] -= 1
+ return ans
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.intersect(nums1=[1, 2, 2, 1], nums2=[2, 2]))
+ print(obj.intersect(nums1=[4, 9, 5], nums2=[9, 4, 9, 8, 4]))