簡體   English   中英

查找數組之間匹配數的最快方法是什么?

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

目前,我正在測試每個整數元素,以找出哪些匹配。 數組在其自己的集合中不包含重復項。 此外,陣列並不總是相等的長度。 有什么技巧可以加快速度嗎? 我這樣做了好幾千次,所以它開始成為我的程序的瓶頸,這是在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);

該集現在僅包含兩個數組中存在的值。

如果這樣的比較是程序中的瓶頸,那么您可能正在使用不適當的數據結構。 最簡單的方法可能是保持數據的排序。 然后,為了找出公共條目,您只需要遍歷兩個數組。 另一種選擇是將數據保存在HashSet中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM