|
| 1 | +package code; |
| 2 | +/* |
| 3 | + * 685. Redundant Connection II |
| 4 | + * 题意:一个图,删掉一个边,使其成为一个根树 |
| 5 | + * 难度:Hard |
| 6 | + * 分类:Tree, Depth-first Search, Union Find, Graph |
| 7 | + * 思路:要把问题想清楚 |
| 8 | + * 判断是否有某个节点父节点有两个, 记为e1, e2 |
| 9 | + * 再判断是否有环 |
| 10 | + * 4中情况,分别想清楚返回什么 |
| 11 | + * 自己没想清楚两种情况的交叉,以为判断完第一步就可直接返回 |
| 12 | + * 如何判断有环,可以利用并查集的思想 |
| 13 | + * Tips:https://leetcode.com/problems/redundant-connection-ii/discuss/108045/C%2B%2BJava-Union-Find-with-explanation-O(n) |
| 14 | + */ |
| 15 | +public class lc685 { |
| 16 | + public int[] findRedundantDirectedConnection(int[][] edges) { |
| 17 | + int[] can1 = {-1, -1}; |
| 18 | + int[] can2 = {-1, -1}; |
| 19 | + int[] parent = new int[edges.length + 1]; |
| 20 | + for (int i = 0; i < edges.length; i++) { |
| 21 | + if (parent[edges[i][1]] == 0) { |
| 22 | + parent[edges[i][1]] = edges[i][0]; |
| 23 | + } else { |
| 24 | + can2 = new int[] {edges[i][0], edges[i][1]}; |
| 25 | + can1 = new int[] {parent[edges[i][1]], edges[i][1]}; |
| 26 | + edges[i][1] = 0; |
| 27 | + } |
| 28 | + } |
| 29 | + for (int i = 0; i < edges.length; i++) { |
| 30 | + parent[i] = i; |
| 31 | + } |
| 32 | + for (int i = 0; i < edges.length; i++) { |
| 33 | + if (edges[i][1] == 0) { |
| 34 | + continue; |
| 35 | + } |
| 36 | + int child = edges[i][1], father = edges[i][0]; |
| 37 | + if (root(parent, father) == child) { //判断father的父节点是不是child |
| 38 | + if (can1[0] == -1) { |
| 39 | + return edges[i]; |
| 40 | + } |
| 41 | + return can1; |
| 42 | + } |
| 43 | + parent[child] = father; |
| 44 | + } |
| 45 | + return can2; |
| 46 | + } |
| 47 | + |
| 48 | + int root(int[] parent, int i) { |
| 49 | + while (i != parent[i]) { //找到根为止 |
| 50 | + parent[i] = parent[parent[i]]; |
| 51 | + i = parent[i]; |
| 52 | + } |
| 53 | + return i; |
| 54 | + } |
| 55 | +} |
0 commit comments