class UnionFind {
public:
UnionFind(int n) {
groups = n;
timestamp = 0;
root.resize(n);
rank.resize(n, 0);
for (int i = 0; i < n; ++i) {
root[i] = i;
}
}
int find(int x) {
if (x == root[x]) {
return x;
}
return root[x] = find(root[x]);
}
void unify(int x, int y, int time) {
int rootX = find(x), rootY = find(y);
if (rootX != rootY) {
if (rank[rootX] < rank[rootY]) {
root[rootX] = rootY;
} else if (rank[rootY] < rank[rootX]) {
root[rootY] = rootX;
} else {
root[rootY] = rootX;
++rank[rootX];
}
--groups;
if (timestamp < time) {
timestamp = time;
}
}
}
int getGroups() {
return groups;
}
int getTimestamp() {
return timestamp;
}
private:
int timestamp;
int groups;
vector<int> root;
vector<int> rank;
};
class Solution {
public:
int earliestAcq(vector<vector<int>> &logs, int n) {
UnionFind uf(n);
sort(logs.begin(), logs.end(), [](vector<int> &log1, vector<int> &log2){ return log1[0] < log2[0]; });
for (auto &log : logs) {
uf.unify(log[1], log[2], log[0]);
}
if (uf.getGroups() != 1) {
return - 1;
}
return uf.getTimestamp();
}
};
My Solution Solution 1: DFS (recursion) The Key Idea for Solving This Coding Question C++ Code /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right;
Jun 6, 2025MyCircularQueueO(k)
Apr 20, 2025O(m)
Mar 4, 2025O(n)n is the length of nums.
Feb 19, 2025or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up