目前,我正在将每个整数元素彼此进行测试,以找出哪些相匹配。数组不包含其自身集合中的重复项。此外,这些数组的长度并不总是相等的。有没有什么技巧可以加快速度?我需要执行这个操作数千次,所以它开始成为我的程序的瓶颈,该程序是使用C#编写的。
目前,我正在将每个整数元素彼此进行测试,以找出哪些相匹配。数组不包含其自身集合中的重复项。此外,这些数组的长度并不总是相等的。有没有什么技巧可以加快速度?我需要执行这个操作数千次,所以它开始成为我的程序的瓶颈,该程序是使用C#编写的。
您可以使用LINQ:
var query = firstArray.Intersect(secondArray);
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++;
}
}
使用 HashSet
var set = new HashSet<int>(firstArray);
set.IntersectWith(secondArray);
该集合现在仅包含两个数组中都存在的值。