LeetCode初级算法-数组-6
题目:两个数组的交集 II
C语言解题
int* intersect(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize) { int min,temp;
*returnSize = 0;
if (nums1Size < nums2Size)
min = nums1Size;
else
min = nums2Size;
int* re = (int*)malloc(sizeof(int)*min);
for (int i = 0; i < nums1Size; i++)
{
for (int j = 0; j < nums2Size; j++)
{
if (nums1[i] == nums2[j])
{
re[(*returnSize)] = nums2[j];
(*returnSize)++;
temp = nums2[j];
nums2[j] = nums2[nums2Size - 1];
nums2[nums2Size - 1] = temp;
nums2Size--;
break;
}
}
}
return re;
}
第二个数组的元素与第一个数组的元素比较,如果一样,就添加到re中,第二个数组的该元素移到最后,数组长度-1(避免重复比较)。