题目来源: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)