2657.找到两个数组的公共数组

keybot
0
2025-08-20

#medium

解题思路

由于数组中的元素不会重复出现,我们只需通过桶来统计两个数组前n个数中相同的的数量并写入res中即可。

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* findThePrefixCommonArray(int* A, int ASize, int* B, int BSize,
                              int* returnSize) {
    int size = ASize < BSize ? ASize : BSize;
    int* res = (int*)malloc(size * sizeof(int));
    int sum[60] = {0};
    for (int i = 0; i < size; i++) {
        int count = 0;
        sum[A[i]]++;
        sum[B[i]]++;
        for (int j = 0; j < 60; j++) {
            if (sum[j] == 2)
                count++;
        }
        res[i] = count;
    }
    *returnSize = size;
    return res;
}