File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Question Link: https://leetcode.com/problems/the-earliest-moment-when-everyone-become-friends/
3+ * Primary idea: Classic Union Find, union every node until the count drops down to 1.
4+ *
5+ * Time Complexity: O(nlogn), Space Complexity: O(n)
6+ *
7+ */
8+
9+ class EarliestMomentFriends {
10+ func earliestAcq( _ logs: [ [ Int ] ] , _ n: Int ) -> Int {
11+ let logs = logs. sorted { $0 [ 0 ] < $1 [ 0 ] }
12+
13+ var roots = Array ( 0 ..< n) , count = n
14+
15+ for log in logs {
16+ let time = log [ 0 ] , friend1 = log [ 1 ] , friend2 = log [ 2 ]
17+
18+ let root1 = find ( friend1, roots)
19+ let root2 = find ( friend2, roots)
20+
21+ if root1 != root2 {
22+ roots [ root1] = root2
23+ count -= 1
24+ }
25+
26+ if count == 1 {
27+ return time
28+ }
29+ }
30+
31+ return - 1
32+ }
33+
34+ private func find( _ node: Int , _ roots: [ Int ] ) -> Int {
35+ var node = node
36+
37+ while node != roots [ node] {
38+ node = roots [ node]
39+ }
40+
41+ return node
42+ }
43+ }
You can’t perform that action at this time.
0 commit comments