C :在另一个数组中找到一个数组的元素数量的最快方法

C++ : Fastest Way to find number of elements of one array in another array

本文关键字:数组 元素 方法 一个 另一个      更新时间:2023-10-16

我有两个数组,一个排序的数组int b[]和其他未分类数组int a[n] having n elements。排序的数组由未分类数组的某些或所有元素制成。现在有m查询。对于 l r 的每个查询值。在每个查询中,我需要找到b[]中存在的a[n]的元素数量。

对于Eg-

N=5 ,M=2
a= [2 5 1 2 3]
b=[3 2 1]
for each m:
l=1 r=5 ->a[1]=1, a[5]=5 -> answer should be 3 as all elements of b i.e 1,2,3 are present in a
l=2 r=4 ->a[2]=5 , a[4]=2 ->answer should be 2 as only 1 and 2 are there in b for given value of l and r for array.

如何找到不超过 o(m * logn)时间复杂性的答案?

注意:阵列不是必需的。也可以使用向量,即它有助于降低时间复杂性或更易于实现代码。

我想你可以做这样的事情

std::map<int,int> c;
for(int i = 0;i<b.length.i++){
   c[b[i]] = 0;
}
for(int i = l; i<=r; i++){
   int number = a[i];
   c[number]++;
}
//Iterate through c with b index and get all number which different than 0. The left is for you

目的是创建B的地图保留索引。然后,在迭代时,您可以增加C值。因此,在此之后,您可以检查C中的每个元素是否具有与零的值不同,意味着A具有B的数量。如果C从零开始并增加1以提高性能,则可以使用数组而不是映射。确保检查如果使用数组,[i]是否可以抛出界限。