leetcode684.冗余连接

依旧是并查集问题,这道题目正好给定顶点数目和边的数目相等,只要找到其中的一条边删除将图转化为树就行,而这个多余的边起始就是并查集的添加过程中二者是同一个根(两个顶点早已经联通了),这时直接返回这条边就行

注意这题中的顶点编号从1开始,为保证一致性,father数组大小为n+1,0索引不使用

cpp 复制代码
class Solution {
private:
    vector<int> father;

    void init() {
        for(int i=0;i<father.size();i++)
            father[i]=i;
    }

    int find(int v) {
        return v==father[v]?v:father[v]=find(father[v]);
    }

    bool isSame(int u,int v) {
        u=find(u);
        v=find(v);
        return u==v;
    }

    bool join(int u,int v) {
        u=find(u);
        v=find(v);
        if(u==v)
            return false;
        else{
            father[v]=u;
            return true;
        }
    }
public:
    vector<int> findRedundantConnection(vector<vector<int>>& edges) {
        int n=edges.size();
        this->father=vector<int>(n+1);
        this->init();

        for(int i=0;i<n;i++){
            int u=edges[i][0];
            int v=edges[i][1];
            if(!this->join(u,v))
                return {u,v};
        }
        return {};
    }
};
相关推荐
凌冰_28 分钟前
数据结构 - 时间空间复杂度(一)
数据结构·算法·软件工程
Pniubi1 小时前
力扣2 . 两数相加
算法·leetcode·职场和发展
戴·菲瑜1 小时前
为什么PPO难以做出顶级棋类引擎
算法·博弈论·rl·ppo
在所不辞兄4 小时前
为什么数字孪生驱动的产线标定需要在线更新机制,而不能一次标定后长期沿用?
人工智能·神经网络·其他·算法·机器学习
文丑颜不良啊7 小时前
LeetCode3401~3420题目解析
java·leetcode
AvocadoZeroOneOI8 小时前
B4500 [GESP202603 三级] 凯撒密码 详细解题报告
c++·算法
文丑颜不良啊9 小时前
LeetCode3421~3440题目解析
java·leetcode
cjz389910 小时前
双指针技巧:覆盖式双指针(原地覆盖)
算法
橘子1313 小时前
【高级数据库】关系代数基本概念
算法
电科_银尘1 天前
【大模型算法与工程 15】手写Self-Attention:Q、K、V与缩放点积
算法