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

Joh*_*res 5 c# arrays optimization match

目前,我正在测试每个整数元素,以找出哪些匹配.数组在其自己的集合中不包含重复项.此外,阵列并不总是相等的长度.有什么技巧可以加快速度吗?我这样做了好几千次,所以它开始成为我的程序的瓶颈,这是在C#中.

Mar*_*ers 6

您可以使用LINQ:

var query = firstArray.Intersect(secondArray);
Run Code Online (Sandbox Code Playgroud)

或者,如果数组已经排序,您可以自己迭代这两个数组:

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++;
    }
}
Run Code Online (Sandbox Code Playgroud)


Jos*_*osh 5

使用HashSet

var set = new HashSet<int>(firstArray);
set.IntersectWith(secondArray);
Run Code Online (Sandbox Code Playgroud)

该集现在仅包含两个数组中存在的值.