簡體   English   中英

高效的數據結構,找到兩個列表的交集

[英]Efficient data structure to find intersection of two lists

我有兩個非常大的List<List<int>> A和B.我需要在這些列表的每個元素之間找到交集。

A[0] = { 1, 2, 3};
B[0] = {2, 3, 4};

Intersection = { 2, 3 };

我的實施:

List<int> intersection = A[0].Intersection(B[0]).ToList();

此解決方案需要很長時間才能執行。 我想知道是否有更好的方法來做到這一點,我可以用更有效的數據結構在更好的時間執行它。

謝謝!

您應該在C# HashSet<T>使用Hashset。 散列集中的查找是O(1)(如果是正確的散列函數並且使用下面的數組)而不是列表的O(n)。

在C#中使用Linq你基本上得到了這個“內置”:如果使用兩個列表, Intersect()將在內部使用一個哈希集來計算O(n)中的交集,而不是O(n ^ 2)。

var intersection = a.Intersect(b).ToList();

使用HashSet(T)的代碼示例.IntersectWith

HashSet<string> lst1 = new HashSet<string> 

     { "id1", "id2", "id3" };

HashSet<string> lst2 = new HashSet<string> 

     { "id2", "id3", "id4" };

// what happens is that, lst1 will be modified by only leaving the intersect items
lst1.IntersectWith(lst2);

PS:我使用了String的示例,但您可以使用自己的整數值。

暫無
暫無

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

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