hello, Could someone let me know what is the difference between the following 2 implementations of Union Find?
Implementation 1:
private static class UnionFind<T> {
private HashMap<T, T> f = new HashMap<>();
T find(T x) {
T y = f.getOrDefault(x, x);
if(y != x) {
y = find(y);
f.put(x, y);
}
return y;
}
void union(T x, T y) {
f.put(find(x), find(y));
}
}Implementation 2:
class Solution {
int[] parent;
int n;
void union(int x, int y) {
int px = find(x);
int py = find(y);
if(px != py) {
parent[px] = py;
n--;
}
}
int find(int x) {
if(parent[x] == x) return x;
parent[x] = find(parent[x]);
return parent[x];
}
}