C :在另一个数组中找到一个数组的元素数量的最快方法
C++ : Fastest Way to find number of elements of one array in another array
我有两个数组,一个排序的数组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]是否可以抛出界限。
相关文章:
- 数组元素打印的递归方法
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 为什么使用数组元素查找最大数字的程序不起作用?
- 数组元素更改值?
- 如何访问宏中定义的数组元素
- 将数组元素递增 1
- C++函数,它将数组、谓词和运算符作为参数,并将运算符应用于满足谓词的数组元素
- 存储指向动态数组元素的指针
- C++通过别名指针以静默方式将错误的类型分配给数组元素
- 在 std::map 中插入数组元素
- 使用指针访问数组元素时出现意外结果
- c++ 使用动态分配运算符反向数组元素
- 为什么在 c++ 中分配 char 数组元素时,分配的字符会被销毁?
- 缺少数组元素问题
- 如何在类中制作 2D 数组元素,然后在其构造函数中指定其维度?
- 创建一个函数来转换数组元素的类型并返回数组的地址
- 删除在结构 c++ 中声明的数组元素
- Getter 和 Setter 用于类 C++ 中的数组元素
- 尝试递归获取数组元素的总和
- 使用SWIG将numpy数组元素(int)传递给c++int