|
| 1 | +# [LeetCode Records](../../README.md) - Question 1101 The Earliest Moment When Everyone Become Friends |
| 2 | + |
| 3 | +### Attempt 1: Use an ArrayList to store the people relationships |
| 4 | +```java |
| 5 | +class Solution { |
| 6 | + public int earliestAcq(int[][] logs, int n) { |
| 7 | + List<Set<Integer>> list = new ArrayList<>(); |
| 8 | + boolean[] checked = new boolean[n]; |
| 9 | + |
| 10 | + Arrays.sort(logs, (l1, l2) -> l1[0] - l2[0]); |
| 11 | + |
| 12 | + for (int[] log : logs) { |
| 13 | + if (!checked[log[1]] && !checked[log[2]]) { |
| 14 | + Set<Integer> set = new HashSet<>(); |
| 15 | + set.add(log[1]); |
| 16 | + set.add(log[2]); |
| 17 | + list.add(set); |
| 18 | + checked[log[1]] = true; |
| 19 | + checked[log[2]] = true; |
| 20 | + } else if (!checked[log[1]]) { |
| 21 | + for (Set<Integer> set : list) { |
| 22 | + if (set.contains(log[2])) { |
| 23 | + set.add(log[1]); |
| 24 | + checked[log[1]] = true; |
| 25 | + break; |
| 26 | + } |
| 27 | + } |
| 28 | + } else if (!checked[log[2]]) { |
| 29 | + for (Set<Integer> set : list) { |
| 30 | + if (set.contains(log[1])) { |
| 31 | + set.add(log[2]); |
| 32 | + checked[log[2]] = true; |
| 33 | + break; |
| 34 | + } |
| 35 | + } |
| 36 | + } else { |
| 37 | + Set<Integer> set1 = null; |
| 38 | + Set<Integer> set2 = null; |
| 39 | + for (Set<Integer> set : list) { |
| 40 | + if (set.contains(log[1])) { |
| 41 | + set1 = set; |
| 42 | + } |
| 43 | + if (set.contains(log[2])) { |
| 44 | + set2 = set; |
| 45 | + } |
| 46 | + |
| 47 | + if (set1 != null && set2 != null) { |
| 48 | + break; |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + if (set1 != set2) { |
| 53 | + set1.addAll(set2); |
| 54 | + list.remove(set2); |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + if (list.size() == 1 && list.get(0).size() == n) { |
| 59 | + return log[0]; |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + return -1; |
| 64 | + } |
| 65 | +} |
| 66 | +``` |
| 67 | +- Runtime: 8 ms (Beats: 18.20%) |
| 68 | +- Memory: 44.33 MB (Beats: 65.72%) |
| 69 | + |
| 70 | +<br> |
0 commit comments