简体   繁体   English

查找数组之间匹配数的最快方法是什么?

[英]What is fastest way to find number of matches between arrays?

Currently, I am testing every integer element against each other to find which ones match. 目前,我正在测试每个整数元素,以找出哪些匹配。 The arrays do not contain duplicates within their own set. 数组在其自己的集合中不包含重复项。 Also, the arrays are not always equal lengths. 此外,阵列并不总是相等的长度。 Are there any tricks to speed this up? 有什么技巧可以加快速度吗? I am doing this thousands of times, so it's starting to become a bottle neck in my program, which is in C#. 我这样做了好几千次,所以它开始成为我的程序的瓶颈,这是在C#中。

You could use LINQ: 您可以使用LINQ:

var query = firstArray.Intersect(secondArray);

Or if the arrays are already sorted you could iterate over the two arrays yourself: 或者,如果数组已经排序,您可以自己迭代这两个数组:

int[] a = { 1, 3, 5 };
int[] b = { 2, 3, 4, 5 };

List<int> result = new List<int>();
int ia = 0;
int ib = 0;
while (ia < a.Length && ib < b.Length)
{
    if (a[ia] == b[ib])
    {
        result.Add(a[ia]);
        ib++;
        ia++;
    }
    else if (a[ia] < b[ib])
    {
        ia++;
    }
    else
    {
        ib++;
    }
}

Use a HashSet 使用HashSet

var set = new HashSet<int>(firstArray);
set.IntersectWith(secondArray);

The set now contains only the values that exist in both arrays. 该集现在仅包含两个数组中存在的值。

If such a comparison is a bottleneck in your program, you are perhaps using an inappropriate data structure. 如果这样的比较是程序中的瓶颈,那么您可能正在使用不适当的数据结构。 The simplest way might be to keep your data sorted. 最简单的方法可能是保持数据的排序。 Then for finding out the common entries, you would need to traverse both arrays only once. 然后,为了找出公共条目,您只需要遍历两个数组。 Another option would be to keep the data in a HashSet. 另一种选择是将数据保存在HashSet中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 找到 INT 数组的第 N 个最大数的最快方法是什么? - What is the fastest way to find Nth biggest number of an INT array? 查找 2 arrays 的出现次数和位置匹配 - Find number of occurrences and positional matches of 2 arrays 在C#中计算两个字节数组之间欧氏距离的最快方法是什么? - What is the fastest way of calculating the Euclidean distance between two byte arrays in C# 查找字节数组数组是否包含另一个字节数组的最快方法是什么? - What is the fastest way to find if an array of byte arrays contains another byte array? 找到文档中最高编号的最快方法 - The fastest way to find highest number in document 比较两个数组是否相同的最快方法是什么? - What's the fastest way to compare two arrays for equality? 什么是在.Net中实现优先级数组收集的最快(插入速度)方式? - What is the fastest (insert speed) way to achieve a prioritized collection of arrays in .Net? LINQ表达式查找两个字符串数组之间是否存在匹配项 - LINQ expression to find if there are any matches between two arrays of string 将数组元素的出现次数限制在之间的最快方法 - Fastest way of putting array elements number of occurrences between limits 查看几个DateTime数组中是否存在任何匹配的最简单方法是什么? - What is the easiest way to seeing if there are any matches across a few DateTime arrays?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM