给定两个数组,编写一个函数来计算它们的交集。
示例 1:
输入: nums1 = [1,2,2,1], nums2 = [2,2]
输出: [2,2]
示例 2:
输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [4,9]
说明:
- 输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。
- 我们可以不考虑输出结果的顺序。
python实现代码:
class Solution:
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
record, result = {}, []
for num in nums1:
record[num] = record.get(num, 0) + 1
for num in nums2:
if num in record.keys() and record[num] > 0:
result.append(num)
record[num] -= 1
return result
if __name__ == '__main__':
test_case1 = [4,9,5]
test_case2 = [9,4,9,8,4]
my_solution = Solution()
print(my_solution.intersect(test_case1, test_case2))
C实现代码:
#include <stdio.h>
#include <stdlib.h>
void arrayPrint(int *array, int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", array[i]);
printf("\n");
}
void quickSort(int *a, int left, int right) //left和right为索引值
{
int key; //存储每次选定的基准数(从最左侧选基准数)
int temp;
int initial = left;
int end = right;
key = a[left];
//***必须有这一部分***//
if (left > right) //因为在递归过程中有减1加1的情况,当其越界时,直接return,不返回任何值,即结束当前程序块
return;
while (left != right) //此时左右index在移动中,若left==right,则跳出循环,将基数归位
{
while (a[right]>=key && left<right) //直到找到小于基准数的值为准
right--;
while (a[left]<=key && left<right)
left++;
if (left < right) //交换左右两侧值,当left=right时,跳出外层while循环
{
temp = a[right];
a[right] = a[left];
a[left] = temp;
}
}
a[initial] = a[left];
a[left] = key; //基数归位
//递归处理归位后的基准数的左右两侧
quickSort(a, initial, left-1); //此时left=right
quickSort(a, left+1, end);
}
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* intersect(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize) {
if (nums1Size <= 0 || nums2Size <= 0)
return NULL;
int newArrSize = nums1Size + nums2Size;
int* newArr = (int*)malloc(sizeof(int)*newArrSize);
int count = 0;
quickSort(nums1, 0, nums1Size-1);
quickSort(nums2, 0, nums2Size-1);
int i = 0, j = 0;
while (i < nums1Size && j < nums2Size) {
if (nums1[i] == nums2[j]) {
newArr[count] = nums1[i];
count++;
i++, j++;
} else if (nums1[i] > nums2[j]) {
j++;
} else
i++;
}
*returnSize = count;
return newArr;
}
int main()
{
int test_case1[] = {1, 2, 2, 3};
int test_case2[] = {2, 2};
int* returnSize = (int*)malloc(sizeof(int));
int* result = intersect(test_case1, 4, test_case2, 2, returnSize);
if (result != NULL)
arrayPrint(result, *returnSize);
free(result);
result = NULL;
free(returnSize);
returnSize = NULL;
return 0;
}