代码之家  ›  专栏  ›  技术社区  ›  JL1

C#-如何按照从最小到最大的顺序重新排列新的HashSet<int>

  •  0
  • JL1  · 技术社区  · 9 年前

    我会先道歉,但我不知道如何确切地说出这个问题。

    我有一段代码目前运行良好,它的唯一目的是找到唯一标识符的所有组合。这很好,但我要做的是创建一个迭代,真正使组合变得独特。

    我的意思如下,您将看到一段简单的代码。将HashSet添加到列表中。然后您将看到一个创建新Hashset列表的方法。我知道如果我可以在每个HashSet中排序,那么它将使自己独一无二。

    static void Main(string[] args)
        {
    
            List<HashSet<int>> myInts = new List<HashSet<int>>();
            myInts.Add(new HashSet<int>{1, 2});
            myInts.Add(new HashSet<int>{2, 1});
        }
    
       private static List<HashSet<int>> RemoveDuplicates(List<HashSet<int>> hash)
        {
            List<HashSet<int>> returnSet = new List<HashSet<int>>();
            for (int i = 0; i < hash.Count; i++)
            {
               //do the order here and add it to the return set
    
            }
    
    
            return returnSet;
    
        }
    

    所以代码是正确的,1,2与2,1不同,但是在我的对象中,它们是相同的组合。因此,我的思路是,如果我可以对数组进行排序,那么HashSet将使其唯一,因为两者都是1,2

    1 回复  |  直到 9 年前
        1
  •  0
  •   BrokenGlass    9 年前

    您不需要订购物品,可以使用 SetEquals 检查集合是否包含相同的元素。

    private static List<HashSet<int>> RemoveDuplicates(List<HashSet<int>> hash)
    {
        List<HashSet<int>> returnSet = new List<HashSet<int>>();
        for (int i = 0; i < hash.Count; i++)
        {
            var isDupe = false;
            //do the order here and add it to the return set
            for (int j = i + 1; j < hash.Count; j++)
            {
                if(hash[i].SetEquals(hash[j]))
                {
                    isDupe = true;
                    break;
                }
            }
            if (!isDupe)
            {
                returnSet.Add(hash[i]);
            }
        }
        return returnSet;
    }
    

    不过,这相当昂贵,假设 设置等于 是O(n),并且有k个集合,这将是O(n*k 2. )