给定两个数组a []和b [] ,任务是在两个给定数组中查找公共元素的数量。请注意,两个数组都包含不同的(单独的)正整数。
例子:
Input: a[] = {1, 2, 3}, b[] = {2, 4, 3}
Output: 2
2 and 3 are common to both the arrays.
Input: a[] = {1, 4, 7, 2, 3}, b[] = {2, 11, 7, 4, 15, 20, 24}
Output: 3
方法:我们将使用3个相同大小的位集。首先,我们将遍历第一个数组,并将位1设置为第一个位集中的a [i] 。
之后,我们将遍历第二个数组并将位1设置为第二个位集中的位置b [i] 。
最后,我们将找到两个位集的按位与,如果结果位集的第i个位置为1,则意味着第一个和第二个位集的i个位置也为1,并且i是两个数组中的公共元素。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
#define MAX 100000
bitset bit1, bit2, bit3;
// Function to return the count of common elements
int count_common(int a[], int n, int b[], int m)
{
// Traverse the first array
for (int i = 0; i < n; i++) {
// Set 1 at position a[i]
bit1.set(a[i]);
}
// Traverse the second array
for (int i = 0; i < m; i++) {
// Set 1 at position b[i]
bit2.set(b[i]);
}
// Bitwise AND of both the bitsets
bit3 = bit1 & bit2;
// Find the count of 1's
int count = bit3.count();
return count;
}
// Driver code
int main()
{
int a[] = { 1, 4, 7, 2, 3 };
int b[] = { 2, 11, 7, 4, 15, 20, 24 };
int n = sizeof(a) / sizeof(a[0]);
int m = sizeof(b) / sizeof(b[0]);
cout << count_common(a, n, b, m);
return 0;
}
Python3
# Python3 implementation of the approach
MAX = 100000
bit1 , bit2, bit3 = 0, 0, 0
# Function to return the count of common elements
def count_common(a, n, b, m) :
# Traverse the first array
for i in range(n) :
global bit1, bit2, bit3
# Set 1 at (index)position a[i]
bit1 = bit1 | (1<
输出:
3