You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
iflet firstSet =setOf(firstElement), let secondSet =setOf(secondElement) { // 1
152
+
if firstSet != secondSet { // 2
153
+
if size[firstSet] < size[secondSet] { // 3
154
+
parent[firstSet] = secondSet // 4
155
+
size[secondSet] += size[firstSet] // 5
156
+
} else {
157
+
parent[secondSet] = firstSet
158
+
size[firstSet] += size[secondSet]
159
+
}
160
+
}
161
+
}
159
162
}
160
-
}
161
-
}
162
163
```
163
164
164
165
Here is how it works:
@@ -167,7 +168,7 @@ Here is how it works:
167
168
168
169
2. Check that the sets are not equal because if they are it makes no sense to union them.
169
170
170
-
3. This is where the size optimization comes in. We want to keep the trees as shallow as possible so we always attach the smaller tree to the root of the larger tree. To determine which is the smaller tree we compare trees by their sizes.
171
+
3. This is where the size optimization comes in (Weighting). We want to keep the trees as shallow as possible so we always attach the smaller tree to the root of the larger tree. To determine which is the smaller tree we compare trees by their sizes.
171
172
172
173
4. Here we attach the smaller tree to the root of the larger tree.
173
174
@@ -185,10 +186,40 @@ Note that, because we call `setOf()` at the start of the method, the larger tree
185
186
186
187
Union with optimizations also takes almost **O(1)** time.
0 commit comments