题目
找出有向图中,多余的连接;确保所有点都相连 && 每个节点只有一个parent(不包含root节点);如果有多个solution,去除靠后的连接;【题目保证去除一个连接,就可以满足要求】
Input: [[1,2], [1,3], [2,3]]
Output: [2,3]
Explanation: The given directed graph will be like this:
1
/ \
v v
2-->3
Input: [[1,2], [2,3], [3,4], [4,1], [1,5]]
Output: [4,1]
Explanation: The given directed graph will be like this:
5 <- 1 -> 2
^ |
| v
4 <- 3
分析
- 隐含条件:1)只有一个parent,如果一个节点有多个parent(这里是最多两个),肯定除去其中一个连接; 如果有两个parent,优先去除后面出现的连接;除非
1. 第二个连接里面包含了root && root只有一个儿子;
2. 第一个连接不可用,这里不可用的含义是:第一个连接的两个节点循环依赖
答案(后续优化)
class Solution {
class UnionFind {
private int union[];
private int rank[];
priva