高效的数据结构,找到两个列表的交集

时间:2013-02-12 03:57:18

标签: c# algorithm data-structures

我有两个非常大的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();

此解决方案需要很长时间才能执行。我想知道是否有更好的方法可以做到这一点以及我可以用来更好地执行它的更有效的数据结构。

谢谢!

2 个答案:

答案 0 :(得分:7)

你应该在C#HashSet<T>中使用Hashset。散列集中的查找是O(1)(如果是正确的散列函数并且使用下面的数组)而不是列表的O(n)。

在C#中使用Linq你基本上得到了这个“内置”:如果使用两个列表,Intersect()将在内部使用一个哈希集来计算O(n)中的交集,而不是O(n ^ 2)。 / p>

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

答案 1 :(得分:1)

使用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,但您可以使用自己的整数值。