【算法分析与设计】【第十八周】684. Redundant Connection

本文解析了LeetCode 684题目的解决方案,介绍了如何使用Kruskal算法和并查集去除无向图中的冗余边,使其成为一棵树。提供了具体的示例和代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目来源:684. https://leetcode.com/problems/redundant-connection/description/

最小生成树,Kruskal算法,贪心,并查集。

684. Redundant Connection

题目大意

通过顶点给定一个无向图,去除冗余的边,使之成为一棵树。
若有多种解法,去除最后给出的边。

Example 1:
Input: [[1,2], [1,3], [2,3]]
Output: [2,3]
Explanation: The given undirected graph will be like this:

   1
  / \
 2 - 3

Example 2:
Input: [[1,2], [2,3], [3,4], [1,4], [1,5]]
Output: [1,4]
Explanation: The given undirected graph will be like this:

5 - 1 - 2
    |   |
    4 - 3

思路

为每条输入的边都给一个递增权值,转化为求最小生成树的问题。

超简单,有没有!

——然后我悲催地发现我只懂得Prim算法和kruskal算法的思想,然而代码写不出来。

!!
!!!

道理我都懂,但是代码怎么写啊好难过好难过。
来学习吧。

Kruskal算法与并查集

学习一下一线码农的博客。

解题代码

我自己写的是Time Limit Exceeded的。。。
借鉴了讨论区fancy1984的代码,也是采用并查集的思想。

class Solution {
public:
    vector<int> findRedundantConnection(vector<vector<int>>& edges) {
        vector<int> p(2000, 0);
        for(int i = 0; i < p.size(); i++ )
            p[i] = i;

        vector<int> res;
        for(auto v : edges ){
            int n1 = v[0], n2 = v[1];
            while(n1 != p[n1]) n1 = p[n1];
            while(n2 != p[n2]) n2 = p[n2];
            if( n1 == n2 )
                res = v;
            else
                p[n1] = n2;
        }
        return res;
    }
};

时间复杂度

O(n)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值