我需要计算两个大字符串数组的交集对应的元素数量,并且速度非常快。
我正在使用以下代码:
arr1[i].Intersect(arr2[j]).Count()
对于 CPU 时间,VS Profiler 指示
- 85.1% 在
System.Linq.Enumerable.Count()
- 0.3% 在
System.Linq.Enumerable.Intersect()
不幸的是,完成所有工作可能需要几个小时。
怎样才能做得更快呢?
您可以使用HashSet
with arr2
HashSet<string> arr2Set = new HashSet<string>(arr2);
arr1.Where(x=>arr2Set.Contains(x)).Count();
------------------
|
|->HashSet's contains method executes quickly using hash-based lookup..
不考虑来自的转换arr2
to arr2Set
,这应该是O(n)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)