博客
关于我
684. Redundant Connection
阅读量:264 次
发布时间:2019-03-01

本文共 1337 字,大约阅读时间需要 4 分钟。

为了解决这个问题,我们需要从给定的图中找出一个额外的边,使得去掉这条边后,图变成一棵树。如果有多个这样的边,我们需要返回最后出现的那条边。

方法思路

我们可以使用并查集(Union-Find)数据结构来解决这个问题。并查集的基本思想是通过路径压缩和按秩合并来高效地管理和查询连通性。具体步骤如下:

  • 初始化父节点数组:每个节点的父节点最初是它自己。
  • 遍历每条边:对于每条边 (u, v),检查这两个节点是否已经连通。
    • 如果连通,说明这条边是多余的,记录下来。
    • 如果不连通,将这两个节点合并到同一个连通块中。
  • 返回最后出现的多余边:在遍历过程中,一旦发现多余边,就记录下来。最后返回这个记录的边。
  • 这种方法确保了在处理每条边时,我们能够高效地检测是否有多余边,并且在遇到多个解时返回最后一个出现的。

    解决代码

    class Solution {    int[] parent;    int n;    public int[] findRedundantConnection(int[][] edges) {        n = edges.length;        parent = new int[n + 1];        for (int i = 1; i <= n; i++) {            parent[i] = i;        }        int[] result = null;        for (int[] edge : edges) {            int u = edge[0];            int v = edge[1];            int rootU = find(u);            int rootV = find(v);            if (rootU == rootV) {                result = edge;            } else {                parent[rootU] = rootV;            }        }        return result;    }    private int find(int x) {        if (parent[x] != x) {            parent[x] = find(parent[x]);        }        return parent[x];    }}

    代码解释

  • 初始化父节点数组parent 数组用于记录每个节点的父节点,初始时每个节点的父节点是它自己。
  • 遍历每条边:对于每条边 (u, v),使用 find 方法分别查找它们的根节点。
  • 检测多余边:如果两个节点的根节点相同,说明已经连通,这条边就是多余的,记录下来。
  • 合并连通块:如果两个节点不连通,将它们的根节点合并,按秩合并(路径压缩)。
  • 返回结果:遍历完所有边后,返回记录的多余边。如果没有多余边(理论上题目中不会有这种情况),返回 null
  • 这种方法确保了在处理每条边时的高效性,并且能够正确返回最后出现的多余边。

    转载地址:http://dbxx.baihongyu.com/

    你可能感兴趣的文章
    STM32工作笔记0032---编写跑马灯实验---寄存器版本
    查看>>
    Static--用法介绍
    查看>>
    ssm旅游信息管理系统的设计与实现bus56(程序+开题)
    查看>>
    order by rand()
    查看>>
    SSM(Spring+SpringMvc+Mybatis)整合开发笔记
    查看>>
    ViewHolder的改进写法
    查看>>
    Orderer节点启动报错解决方案:Not bootstrapping because of 3 existing channels
    查看>>
    org.apache.axis2.AxisFault: org.apache.axis2.databinding.ADBException: Unexpected subelement profile
    查看>>
    sql查询中 查询字段数据类型 int 与 String 出现问题
    查看>>
    org.apache.commons.beanutils.BasicDynaBean cannot be cast to ...
    查看>>
    org.apache.dubbo.common.serialize.SerializationException: com.alibaba.fastjson2.JSONException: not s
    查看>>
    sqlserver学习笔记(三)—— 为数据库添加新的用户
    查看>>
    org.apache.http.conn.HttpHostConnectException: Connection to refused
    查看>>
    org.apache.ibatis.binding.BindingException: Invalid bound statement错误一例
    查看>>
    org.apache.ibatis.exceptions.PersistenceException:
    查看>>
    org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
    查看>>
    org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
    查看>>
    org.apache.poi.hssf.util.Region
    查看>>
    org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
    查看>>
    org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
    查看>>