---
# System prepended metadata

title: 1101. The Earliest Moment When Everyone Become Friends
tags: [Leetcode, Union Find, Medium]

---

# 1101. The Earliest Moment When Everyone Become Friends
###### tags: `Leetcode` `Medium` `Union Find`
Link: https://leetcode.com/problems/the-earliest-moment-when-everyone-become-friends/
## 思路
先按时间排序
找到group=1的第一个时间
## Code
```java=
class Solution {
    int[] fa;
    int group;
    public int earliestAcq(int[][] logs, int n) {
        fa = new int[n];
        group = n;
        Arrays.sort(logs, (a,b)->(a[0]-b[0]));
        for(int i=0; i<n; i++) fa[i] = i;
        for(int[] log:logs){
            combine(log[1], log[2]);
            if(group==1) return log[0];
        }
        return -1;
    }
    private int find(int a){
        if(fa[a]==a) return a;
        return fa[a] = find(fa[a]);
    }
    private void combine(int a, int b){
        a = find(a);
        b = find(b);
        if(a==b) return;
        group--;
        fa[b]=a;
    }
}
```