嵌套List的合并元素在唯一列表c#中

Mar*_*ina 4 c# list

我有一个嵌套的List,例如:

List<List<int>> myList = new List<List<int>>();
myList.Add(new List<int> { 2, 7, 3 });
myList.Add(new List<int> { 4, 6});
myList.Add(new List<int> { 2, 5, 1 });
myList.Add(new List<int> { 7, 0, 2 });
myList.Add(new List<int> { 4, 9 });
Run Code Online (Sandbox Code Playgroud)

我想合并至少有一个共同元素的所有列表,以便输出将是一个List<List<int>>元素:

List<int> 2, 7, 3, 5, 1, 0
List<int> 4,6,9
Run Code Online (Sandbox Code Playgroud)

谢谢

Rot*_*tem 7

您可以使用HashSet解决方案,但我确信可以提高效率:

public static void Main(string[] args)
{
    List<List<int>> myList = new List<List<int>>();
    myList.Add(new List<int> { 2, 7, 3 });
    myList.Add(new List<int> { 4, 6});
    myList.Add(new List<int> { 2, 5, 1 });
    myList.Add(new List<int> { 7, 0, 2 });
    myList.Add(new List<int> { 4, 9 });
    var result = FindCommonSets(myList);
}

static List<HashSet<T>> FindCommonSets<T>(IEnumerable<IEnumerable<T>> data)
{
    List<HashSet<T>> sets = new List<HashSet<T>>();
    bool anyModified = false;
    foreach (var list in data)
    {
        //find a set which already overlaps this list.
        var set = sets.FirstOrDefault(s => s.Overlaps(list));
        if (set != null)
        {
            //if we find one, dump all the elements of this list into the set.
            set.UnionWith(list);
            anyModified = true;
        }
        else
        {
            //if not, add a new set based on this list.
            sets.Add(new HashSet<T>(list));
        }
    }
    if (anyModified)
    {
        //run the whole thing again with the new data if anything was changed in this iteration.
        return FindCommonSets(sets);
    }
    return sets;
}
Run Code Online (Sandbox Code Playgroud)

编辑:在注释中出现的问题后更改为递归实现.

  • 我认为修复将是使用新集合重复合并,直到找不到需要合并的集合. (3认同)
  • 棘手的问题.您的解决方案适用于OP中的输入示例,但它不适用于:`{2,7,3},{4,6},{5,1},{7,0,2},{4,例如,9},{2,5}.在这种情况下,最后一个{2,5}应该导致两个已经存在的集合合为一个,这与您的代码不同. (2认同)