当前位置:网站首页>leetcode-684:冗余连接
leetcode-684:冗余连接
2022-07-30 17:38:00 【菊头蝙蝠】
题目
树可以看成是一个连通且 无环 的 无向 图。
给定往一棵 n 个节点 (节点值 1~n) 的树中添加一条边后的图。添加的边的两个顶点包含在 1 到 n 中间,且这条附加的边不属于树中已存在的边。图的信息记录于长度为 n 的二维数组 edges ,edges[i] = [ai, bi] 表示图中在 ai 和 bi 之间存在一条边。
请找出一条可以删去的边,删除后可使得剩余部分是一个有着 n 个节点的树。如果有多个答案,则返回数组 edges 中最后出现的边。
示例 1:

输入: edges = [[1,2], [1,3], [2,3]]
输出: [2,3]
示例 2:
输入: edges = [[1,2], [2,3], [3,4], [1,4], [1,5]]
输出: [1,4]

解题
方法一:并查集
遍历edge,如果发现已经连同的,那么更新res。
最后得到的res,一定是最后出现的并且已连通的。
class UnionFind{
private:
vector<int> parent;
public:
UnionFind(int n){
parent.resize(n);
iota(parent.begin(),parent.end(),0);
}
int find(int index){
if(parent[index]==index) return index;
return parent[index]=find(parent[index]);
}
bool unite(int index1,int index2){
int p1=find(index1);
int p2=find(index2);
if(p1==p2) return false;//如果已经连通,那么返回false
else{
parent[p1]=p2;
return true;
}
}
};
class Solution {
public:
vector<int> findRedundantConnection(vector<vector<int>>& edges) {
vector<int> res;
int n=edges.size();
UnionFind uf(n+1);
for(vector<int>& edge:edges){
if(!uf.unite(edge[0],edge[1])) res=edge;
}
return res;
}
};
边栏推荐
- KDD 2020 | 深入浅出优势特征蒸馏在淘宝推荐中的应用
- ERROR 2003 (HY000) Can't connect to MySQL server on 'localhost3306' (10061)Solution
- 想要写出好的测试用例,先要学会测试设计
- Google earth engine如何实现我们时间列表的排列和选取
- CMake库搜索函数居然不搜索LD_LIBRARY_PATH
- Informatics Olympiad All-in-One 1966: [14NOIP Popularization Group] Scale Simplification | Luogu P2118 [NOIP2014 Popularization Group] Scale Simplification
- Redis缓存穿透-热点缓存并发重建-缓存与数据库双写不一致-缓存雪崩
- C陷阱与缺陷 第6章 预处理器 6.4 宏并不是类型定义
- 阿里SIM-基于检索的用户行为兴趣CTR模型(Search-based user Interest Model(SIM))
- 数据预处理:离散特征编码方法
猜你喜欢

知识蒸馏2:目标检测中的知识蒸馏

一个 15 年 SAP ABAP 开发人员分享的 SAPGUI 一些个性化设置和实用小技巧试读版

宝塔搭建PHP自适应懒人网址导航源码实测

图卷积神经网络的数学原理——谱图理论和傅里叶变换初探

BCryptPasswordEncoder的使用及原理

Wincc报表教程(SQL数据库的建立,wincc在数据库中保存和查询数据,调用Excel模板把数据保存到指定的位置和打印功能)

顺通海关查验预约综合管理系统

【AAAI2020】阿里DMR:融合Matching思想的深度排序模型

Insert data into MySQL in C language

un7.30:linux——如何在docker容器中安装MySQL?
随机推荐
浅谈在线编辑器中增量编译技术的应用
记者卧底
莫队--优雅的暴力
查询表中开始日期与结束日期
C陷阱与缺陷 第6章 预处理器
web服务通过用户访问请求判断设备来源
Error EPERM operation not permitted, mkdir 'Dsoftwarenodejsnode_cache_cacach Two solutions
什么是工业射线照相设备?
Ecplise执行C语言报错:cannot open output file xxx.exe: Permission denied
阿里巴巴CAN:Embedding前置的特征交互新思路
Error occurred while trying to proxy request The project suddenly can't get up
基于模糊PID的液压舵机伺服系统
SYSCALL SWAPGS
简易的命令行入门教程
Mo Team - Elegant Violence
LeetCode318: Maximum product of word lengths
Analysis and Simulation of Short Circuit Fault in Power System Based on MATLAB
Summary of String Copy, Concatenation, Comparison and Split Functions (1)
顺通海关查验预约综合管理系统
C# 连接SQL Sever 数据库与数据查询实例 数据仓库