---
title: 'LeetCode 349. Intersection of Two Arrays'
disqus: hackmd
---
# LeetCode 349. Intersection of Two Arrays
## Description
Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.
## Example
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]
Explanation: [4,9] is also accepted.
## Constraints
1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 1000
## Answer
此題可用hash table,第一for先初始化table,第二for開始給值,第三for就看是否為0,如不是就表示為共同項即為答案。記得將檢查完的項初始為0,否則可能會再抓到一樣的項目就會造成重複。
```Cin=
int* intersection(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize){
if(nums1Size==0){*returnSize = 0; return nums1;}
if(nums2Size==0){*returnSize = 0; return nums2;}
int i = 0,idx = 0;
*returnSize = 0;
int *check = (int*)malloc(sizeof(int)*1000);
int *ans = (int*)malloc(sizeof(int));
for(i = 0;i<1000;i++){check[i] = 0;}
for(i = 0;i<nums1Size;i++){check[ nums1[i] ]++;}
for(i = 0;i<nums2Size;i++){
if(check[ nums2[i] ]!=0){
ans = (int*)realloc(ans , sizeof(int)*(idx+1));
ans[idx] = nums2[i];
check[ nums2[i] ] = 0;
idx++;
(*returnSize)++;
}
}
free(check);
return ans;
}
```
## Link
https://leetcode.com/problems/intersection-of-two-arrays/
###### tags: `Leetcode`