并查集(Union Find)
作者:互联网
定义
顾名思义(看英文),就是并集,查找,即找到父节点,然后取并集;
题目:LeetCode 547. 省份数量
解决方法:参照B站Up主,塔罗兔
代码:
- 基础版本
class Solution {
public:
vector<int> fathers;
int find(int i) {
while (fathers[i] != i) {
i = fathers[i];
}
return i;
}
void uni(int i, int j) {
int f1 = find(i);
int f2 = find(j);
fathers[f2] = f1;
}
int findCircleNum(vector<vector<int>>& isConnected) {
int n = isConnected.size();
// 初始化父节点
for (int i = 0; i < n; i++) {
fathers.push_back(i);
}
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (isConnected[i][j]) {
uni(i, j);
}
}
}
int count = 0;
for (int i = 0; i < n; i++) {
if (fathers[i] == i) count++;
}
return count;
}
};
- 优化:
class Solution {
public:
vector<int> fathers;
vector<int> ranks;
int find(int i) {
while (fathers[i] != i) {
i = fathers[i];
}
return i;
}
void uni(int i, int j) {
int f1 = find(i);
int f2 = find(j);
// fathers[f2] = f1;
if (ranks[f1] == ranks[f2]) {
fathers[f2] = f1;
ranks[f1]++;
} else if (ranks[f1] > ranks[f2]) {
fathers[f2] = f1;
} else {
fathers[f1] = f2;
}
}
int findCircleNum(vector<vector<int>>& isConnected) {
int n = isConnected.size();
// 初始化父节点
for (int i = 0; i < n; i++) {
fathers.push_back(i);
ranks.push_back(1);
}
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (isConnected[i][j]) {
uni(i, j);
}
}
}
int count = 0;
for (int i = 0; i < n; i++) {
if (fathers[i] == i) count++;
}
return count;
}
};
PS: 代码运行的时间反而增加了,在LeetCode[CN] 版本中.
标签:f1,f2,Union,fathers,查集,++,int,ranks,Find 来源: https://www.cnblogs.com/ache/p/16519379.html