【问题标题】:Does Java's Set's implement the UnionFind algorithm?Java Set 是否实现了 Union Find 算法?
【发布时间】:2012-01-12 10:15:46
【问题描述】:

我知道 Wikipedia 上的 Union Find 算法,并且可以找到它们的小型实现,但是 Java 本身是否对其 Set 使用了类似的算法?如果是这样,我宁愿使用 Java Sets 而无需重新编码轮子...

【问题讨论】:

  • 你的意思是不相交集操作吗?

标签: java algorithm math data-structures


【解决方案1】:

Java 的 Set 接口支持与 Union Find 结构完全不同的操作(因此适用于完全不同的用例)。

【讨论】:

  • Java 有 Disjoin-Set 数据结构吗?现在我使用 HashMap 从单纯形到复合体,每个复合体都记住它的单纯形集
  • @propaganda:标准 API 中没有任何内容,但我相信您可以在 Internet 上找到实现。
【解决方案2】:

AFAIK 不,要创建两个集合的并集,常见的方法是复制一个集合并添加第二个集合的所有元素。 (或将两个集合的所有元素复制到同一个集合)例如

Set<E> set1, set2;

Set<E> union = new HashSet<E>(set1);
union.addAll(set2);

【讨论】:

    【解决方案3】:

    我同意第一个答案。此外,要在 Set 中查找元素,您应该使用 contains 方法。它的签名是:

    public boolean contains(Object o)
    
    Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e)).
    
    Specified by:
        contains in interface Collection<E>
    
    Parameters:
        o - element whose presence in this set is to be tested. 
    Returns:
        true if this set contains the specified element. 
    Throws:
        ClassCastException - if the type of the specified element is incompatible with this set (optional). 
        NullPointerException - if the specified element is null and this set does not support null elements (optional).
    

    此外,这三个 Set 的实现方式完全不同。将其元素存储在哈希表中的 HashSet 是性能最好的实现;但是它不保证迭代的顺序。 TreeSet 将其元素存储在红黑树中,根据元素的值对其元素进行排序;它比 HashSet 慢得多。 LinkedHashSet 被实现为一个带有链表的哈希表,它根据元素插入集合的顺序(插入顺序)对其元素进行排序。 LinkedHashSet 将其客户从 HashSet 提供的未指定的、通常混乱的排序中解放出来,而代价只是略高一些。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-22
      • 1970-01-01
      • 2023-03-13
      • 2017-09-19
      • 2018-12-04
      • 2019-08-12
      相关资源
      最近更新 更多