题目

在本问题中, 树指的是一个连通且无环的无向图。
输入一个图,该图由一个有着N个节点 (节点值不重复1, 2, …, N) 的树及一条附加的边构成。附加的边的两个顶点包含在1到N中间,这条附加的边不属于树中已存在的边。
结果图是一个以边组成的二维数组。每一个边的元素是一对[u, v] ,满足 u < v,表示连接顶点u 和v的无向图的边。
返回一条可以删去的边,使得结果图是一个有着N个节点的树。如果有多个答案,则返回二维数组中最后出现的边。答案边 [u, v] 应满足相同的格式 u < v。
示例 1:
输入: [[1,2], [1,3], [2,3]]
输出: [2,3]
解释: 给定的无向图为:
1
/ \
2 - 3
示例 2:
输入: [[1,2], [2,3], [3,4], [1,4], [1,5]]
输出: [1,4]
解释: 给定的无向图为:
5 - 1 - 2
| |
4 - 3
注意:
输入的二维数组大小在 3 到 1000。
二维数组中的整数在1到N之间,其中N是输入数组的大小。
更新(2017-09-26):
我们已经重新检查了问题描述及测试用例,明确图是无向 图。对于有向图详见冗余连接II。对于造成任何不便,我们深感歉意。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/redundant-connection
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

1.并查集
找到环 删除任意一条边

  1. /**
  2. * @param {number[][]} edges
  3. * @return {number[]}
  4. */
  5. var findRedundantConnection = function (edges) {
  6. //并查集
  7. //找到环 任意删除一条边
  8. const uf = new UnionFind()
  9. for (item of edges) {
  10. uf.add(item[0])
  11. uf.add(item[1])
  12. }
  13. for (item of edges) {
  14. if (uf.union(item[0], item[1])) {
  15. console.log(uf.parent)
  16. return item
  17. }
  18. }
  19. };
  20. class UnionFind {
  21. constructor() {
  22. this.parent = {}
  23. }
  24. find(x) {
  25. let x_root = x
  26. while (this.parent[x_root] !== -1) {
  27. x_root = this.parent[x_root]
  28. }
  29. //路径压缩
  30. while (x_root !== x) {
  31. let originParent = this.parent[x]
  32. this.parent[x] = x_root
  33. x = originParent
  34. }
  35. return x_root
  36. }
  37. union(x, y) {
  38. let x_root = this.find(x)
  39. let y_root = this.find(y)
  40. if (x_root === y_root) {
  41. return true
  42. }
  43. this.parent[x_root] = y_root
  44. return false
  45. }
  46. add(x) {
  47. if (!this.parent[x]) {
  48. this.parent[x] = -1
  49. }
  50. }
  51. }