我有两个非常大的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();
这个解决方案时间非常长。我想知道是否有更好的方法来做这件事以及是否有更有效的数据结构可以在更短的时间内执行。
谢谢!
我有两个非常大的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();
这个解决方案时间非常长。我想知道是否有更好的方法来做这件事以及是否有更有效的数据结构可以在更短的时间内执行。
谢谢!
HashSet<T>
,在哈希集合中进行查找的时间复杂度为O(1)(如果使用了合适的哈希函数和数组作为底层数据结构),而列表的时间复杂度则为O(n)。Intersect()
会在内部使用哈希集合来计算交集,时间复杂度为O(n),而不是使用两个列表时的O(n^2)。var intersection = a.Intersect(b).ToList();
.ToList()
会产生额外的O(N)复杂度,我该如何避免它呢? - John LathamHashSet<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:我使用了字符串的示例,但您可以使用自己的整数值。