Commit 8ef71992 authored by anqiwa's avatar anqiwa 😲
Browse files

add 684

parent 378bfcd1
......@@ -7,4 +7,6 @@
</br></br>
[Union_Find](https://gitlab.eecs.umich.edu/anqiwa/myleetcodesolu/-/tree/master/Union_Find)
[547.Friend_Circles](https://gitlab.eecs.umich.edu/anqiwa/myleetcodesolu/-/tree/master/Union_Find/547.Friend-Circles)
\ No newline at end of file
[547.friend circles/ number of provinces](https://gitlab.eecs.umich.edu/anqiwa/myleetcodesolu/-/tree/master/Union_Find/547.Friend-Circles) (M)
[648.redundant connection]()
\ No newline at end of file
/*
* @lc app=leetcode id=684 lang=cpp
*
* [684] Redundant Connection
*/
// @lc code=start
class Solution
{
unordered_map<int, int> father;
public:
vector<int> findRedundantConnection(vector<vector<int>> &edges)
{
const int n = edges.size();
for (int i = 0; i < n; ++i)
{
father[i + 1] = i + 1;
}
for (int i = 0; i < n; ++i)
{
auto &e = edges[i];
if (findFather(e[0]) != findFather(e[1]))
{
unionfy(e[0], e[1]);
}
else
{
return e;
}
}
return {0, 0};
}
int findFather(int x)
{
if (x != father[x])
father[x] = findFather(father[x]);
return father[x];
}
void unionfy(int i, int j)
{
int x = findFather(i);
int y = findFather(j);
father[x] = y;
}
};
// @lc code=end
# 684 Redundant Connection
这题十分好像,就是用union find的套路走流程就可以做出, 是对加强union find 套路掌握很好的练习,union find的基本模板可以参考 ```lc547```
基本思路:
每看到一个edge,如果两个点不是在同一个 ```connected component```, 就把他们用union合并成在一个 connected componen; 如果两个点已经在同一个 connected component 了, 则当前的 edge e 为多余,直接 return 他就好了
```cpp
for (int i = 0; i < n; ++i)
{
auto &e = edges[i];
if (findFather(e[0]) != findFather(e[1]))
{
unionfy(e[0], e[1]);
}
else
{
return e;
}
}
```
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment