describe
Given two arrays nums1
and sum nums2
, return their intersection . Each element in the output must be unique . We can ignore the order of the output results. (1 <= nums1.length, nums2.length <= 1000, 0 <= nums1[i], nums2[i] <= 1000)
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]
Explanation: [4,9] is also passable
Idea: Create a new array, use the value of an input array as the subscript of the new array, and set the value of the new array corresponding to the subscript i to 1, indicating that there is 1 number i. value, the array value corresponding to the subscript in the newly created array is 1, set its value to 2, indicating that the number i exists in both input arrays, and then put the subscript with a value of 2 in the newly created array into the new array middle.
C language
int* intersection(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize){
int* arr=(int*)malloc(sizeof(int)*1000);
//The number of identical elements in the two collections
int count=0;
for(int i=0;i<nums1Size;i++)
{
arr[nums1[i]]=1;
}
for(int i=0;i<nums2Size;i++)
{
//num2[i] is the common element of the two arrays
if(arr[nums2[i]]==1)
{
arr[nums2[i]]=2;
count++;
}
}
*returnSize=count;
//store the collection of two arrays
int* p=(int*)malloc(sizeof(int)*(nums1Size>nums2Size?nums1Size:nums2Size));
int j=0;
for(int i=0;i<1000;i++)
{
if(arr[i]==2)
{
p[j++]=i;
count--;
}
if(count==0)
break;
}
return p;
}
Java
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
int[] temp = new int[1001];
for (int i = 0; i < nums1.length; i++) {
if (temp[nums1[i]]==0) temp[nums1[i]]=1;
}
int num = 0;
for (int i = 0; i < nums2.length; i++) {
if (temp[nums2[i]]==1){
temp[nums2[i]]=2;
num++;
}
}
int[] res = new int[num];
for (int i = 0; i < 1001; i++) {
if (temp[i]==2){
res[--num] = i;
}
}
return res;
}
}