leetcode-349. 两个数组的交集

发布时间 2023-05-09 13:12:34作者: TimeNoMuch
return nums1.Intersect(nums2);

题意:给定两个数组,编写一个函数来计算它们的交集。 c#可以用linq自带的方法返回,顺便看了下微软的内部实现:

private static IEnumerable<TSource> IntersectIterator<TSource>(IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource>? comparer)
        {
            var set = new HashSet<TSource>(second, comparer);
 
            foreach (TSource element in first)
            {
                if (set.Remove(element))
                {
                    yield return element;
                }
            }
        }