|
| 1 | +// https://leetcode.com/problems/the-earliest-moment-when-everyone-become-friends |
| 2 | +// M = |logs| |
| 3 | +// T: O(N + M logM + M al(N)) al = inverse Ackermann function |
| 4 | +// S: O(N + logM) |
| 5 | + |
| 6 | +import java.util.Arrays; |
| 7 | +import java.util.Comparator; |
| 8 | + |
| 9 | +public class TheEarliestMomentWhenEveryoneBecomeFriends { |
| 10 | + private static final class DisjointSet { |
| 11 | + private final int[] root, rank; |
| 12 | + |
| 13 | + public DisjointSet(int size) { |
| 14 | + root = new int[size]; |
| 15 | + rank = new int[size]; |
| 16 | + for (int i = 0 ; i < size ; i++) { |
| 17 | + root[i] = i; |
| 18 | + rank[i] = 1; |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + public int find(int num) { |
| 23 | + if (num == root[num]) { |
| 24 | + return num; |
| 25 | + } |
| 26 | + return root[num] = find(root[num]); |
| 27 | + } |
| 28 | + |
| 29 | + public boolean areConnected(int x, int y) { |
| 30 | + return find(x) == find(y); |
| 31 | + } |
| 32 | + |
| 33 | + public void union(int x, int y) { |
| 34 | + final int rootX = find(x), rootY = find(y); |
| 35 | + if (rootX == rootY) { |
| 36 | + return; |
| 37 | + } |
| 38 | + if (rank[rootX] > rank[rootY]) { |
| 39 | + root[rootY] = rootX; |
| 40 | + } else if (rank[rootX] < rank[rootY]) { |
| 41 | + root[rootX] = rootY; |
| 42 | + } else { |
| 43 | + root[rootY] = rootX; |
| 44 | + rank[rootX]++; |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + public int earliestAcq(int[][] logs, int n) { |
| 50 | + final DisjointSet disjointSet = new DisjointSet(n); |
| 51 | + Arrays.sort(logs, Comparator.comparingInt(a -> a[0])); |
| 52 | + for (int[] log : logs) { |
| 53 | + if (!disjointSet.areConnected(log[1], log[2])) { |
| 54 | + disjointSet.union(log[1], log[2]); |
| 55 | + n--; |
| 56 | + if (n == 1) { |
| 57 | + return log[0]; |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + return -1; |
| 62 | + } |
| 63 | +} |
0 commit comments