Try   HackMD

1101. The Earliest Moment When Everyone Become Friends


My Solution

The Key Idea for Solving This Coding Question

C++ Code

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(); } };

Time Complexity

Space Complexity

Miscellaneous