--- tags: leetcode --- # [1101. The Earliest Moment When Everyone Become Friends](https://leetcode.com/problems/the-earliest-moment-when-everyone-become-friends/description/) --- # My Solution ## The Key Idea for Solving This Coding Question ## C++ Code ```cpp= 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 <!-- # Test Cases ``` [[20190101,0,1],[20190104,3,4],[20190107,2,3],[20190211,1,5],[20190224,2,4],[20190301,0,3],[20190312,1,2],[20190322,4,5]] 6 ``` ``` [[0,2,0],[1,0,1],[3,0,3],[4,1,2],[7,3,1]] 4 ``` * Wrong Answer ``` [[7,3,1],[2,3,0],[3,2,1],[6,0,1],[0,2,0],[4,3,2]] 4 ``` * Wrong Answer ``` [[9,0,3],[0,2,7],[12,3,1],[5,5,2],[3,4,5],[1,5,0],[6,2,4],[2,5,3],[7,7,3]] 8 ``` -->