We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 1f62d20 commit ebb86e5Copy full SHA for ebb86e5
Union-Find/并查集(Union-Find).md
@@ -0,0 +1,34 @@
1
+# 并查集(Union-Find)
2
+
3
+一种树型的数据结构,用于处理一些不交集(Disjoint Sets)的合并及查询问题。不交集指的是一系列没有重复元素的集合。主要是支持两种操作:
4
5
+- **合并(Union)**:将两个集合合并成一个集合。
6
+- **查找(Find)**:确定某个元素属于哪个集合。通常是返回集合内的一个「代表元素」。
7
8
+```go
9
+type unionFind struct {
10
+ father []int
11
+}
12
13
+func (u unionFind) init(nums []int) {
14
+ for i := range nums {
15
+ u.father[i] = i
16
+ }
17
18
19
+func (u unionFind) find(x int) int {
20
+ if u.father[x] == x {
21
+ return x
22
23
+ root := u.find(u.father[x]) // 状态压缩,找到根节点,而不是一层一层找父节点
24
+ u.father[x] = root
25
+ return root
26
27
+func (u unionFind) union(x, y int) {
28
+ xRoot, yRoot := u.find(x), u.find(y)
29
+ if xRoot != yRoot {
30
+ u.father[yRoot] = xRoot
31
32
33
+```
34
0 commit comments