Java 的 Set 是否实现了 UnionFind 算法?
我从 Wikipedia 知道 Union Find 算法,并且可以找到它们的小实现,但是 Java 本身是否对其 Set 使用类似的算法?如果是这样,我更愿意使用 Java Sets 而不重新编码轮子......
I know the Union Find algorithm from Wikipedia, and can find small implementations of them, but does Java itself use a similar algorithm for its Set's? If so I'd prefer to use Java Sets without recoding the wheel...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Java 的 Set 接口支持与 Union Find 结构完全不同的操作(因此适用于完全不同的用例)。
Java's Set interface supports completely different operations (and is therefore appropriate for completely different use cases) that a Union Find structure.
AFAIK 不,要创建两个集合的并集,常见的方法是复制一个集合并添加第二个集合的所有元素。 (或者将两个集合的所有元素复制到同一集合)例如
AFAIK No, to create a union of two sets, the common approach is to copy one set and add all the elements of the second. (Or copy all the element of both sets to the same set) e.g.
我同意第一个答案。此外,要查找 Set 中的元素,您应该使用 contains 方法。它的签名是:
另外,这三个 Set 实现的制作方式完全不同。 HashSet 将其元素存储在哈希表中,是性能最好的实现;但是它不保证迭代的顺序。 TreeSet 将其元素存储在红黑树中,并根据元素的值对元素进行排序;它比 HashSet 慢得多。 LinkedHashSet 是作为一个哈希表实现的,其中有一个链表贯穿其中,它根据元素插入集合的顺序(插入顺序)对其元素进行排序。 LinkedHashSet 使其客户免受 HashSet 提供的未指定的、通常混乱的排序的影响,但成本仅略高一些。
I agree with the first answer. In addition, to find an element in a Set, you should use the contains method. Its signature is:
In addition, the three Set implementations are quite differently made. HashSet, which stores its elements in a hash table, is the best-performing implementation; however it makes no guarantees concerning the order of iteration. TreeSet, which stores its elements in a red-black tree, orders its elements based on their values; it is substantially slower than HashSet. LinkedHashSet, which is implemented as a hash table with a linked list running through it, orders its elements based on the order in which they were inserted into the set (insertion-order). LinkedHashSet spares its clients from the unspecified, generally chaotic ordering provided by HashSet at a cost that is only slightly higher.