---
title: 'LeetCode 350. Intersection of Two Arrays II'
disqus: hackmd
---
# LeetCode 350. Intersection of Two Arrays II
## Description
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.
## Example
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
Explanation: [9,4] is also accepted.
## Constraints
1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 1000
## Answer
此題可用hash table,第一for先初始化table,第二for開始給值,第三for就看是否為-1,如不是就表示為共同項即為答案。記得每登記完一次答案就要--,如此才能計算出現的次數。
```Cin=
//2021_11_30
int* intersect(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize){
int i = 0, max = 1001;
*returnSize = 0;
int *temp = (int*)malloc(sizeof(int)*max);
int *ans = (int*)malloc(sizeof(int)*max);
for(i = 0; i < max; i++){temp[i] = -1;}
for(i = 0; i < nums1Size; i++){temp[ nums1[i] ]++;}
for(i = 0; i < nums2Size; i++){
if(temp[ nums2[i] ] != -1){
ans[*returnSize] = nums2[i];
temp[ nums2[i] ]--;
(*returnSize)++;
}
}
free(temp);
return ans;
}
```
## Link
https://leetcode.com/problems/intersection-of-two-arrays-ii/
###### tags: `Leetcode`