How do I do an integer list intersection while keeping duplicates?

后端 未结 6 1513
别跟我提以往
别跟我提以往 2020-12-31 09:11

I\'m working on a Greatest Common Factor and Least Common Multiple assignment and I have to list the common factors. Intersection() won\'t work because that removes duplicat

6条回答
  •  难免孤独
    2020-12-31 09:56

    Are you looking for something like this? It should be pretty-much O(n+m), where n is the number of items in first and m is the number of items in second.

    public static IEnumerable Overlap(this IEnumerable first,
        IEnumerable second, IEqualityComparer comparer = null)
    {
        // argument checking, optimisations etc removed for brevity
    
        var dict = new Dictionary(comparer);
    
        foreach (T item in second)
        {
            int hits;
            dict.TryGetValue(item, out hits);
            dict[item] = hits + 1;
        }
    
        foreach (T item in first)
        {
            int hits;
            dict.TryGetValue(item, out hits);
            if (hits > 0)
            {
                yield return item;
                dict[item] = hits - 1;
            }
        }
    }
    

提交回复
热议问题