Loading

LeetCode 547. 省份数量

 

思路

方法:并查集

并查集模板题。注意:并查集路径压缩后的查找根节点函数的最坏复杂度为O(logn),平均时间复杂度为 O(α(n)),这里α 表示阿克曼函数的反函数,在宇宙可观测的 n 内(例如宇宙中包含的粒子总数),α(n)不会超过 5。

具体解释见这里:并查集各种情况下的时间复杂度

 1 class Solution {
 2 private:
 3     vector<int> tree;   //并查集
 4     int circleNum = 0;
 5     int n;
 6 public:
 7     int findCircleNum(vector<vector<int>>& isConnected) {
 8         n = isConnected.size();
 9         tree = vector<int>(n, -1);
10         
11         for(int i = 0; i < n; ++i) {
12             for(int j = i+1; j < n; ++j) {
13                 if(isConnected[i][j] == 1) {
14                     //判断i和j是否在同一个集合当中
15                     int ri = findRoot(i);
16                     int rj = findRoot(j);
17                     if(ri != rj) {
18                         tree[ri] = rj;
19                     }
20                 }
21             }
22         }
23 
24         for(int i = 0; i < n; ++i) {
25             if(tree[i] == -1)
26                 circleNum++;
27         }
28 
29         return circleNum;
30     }
31 
32     //并查集的查找
33     int findRoot(int x) {
34         if(tree[x] == -1)
35             return x;
36         
37         //路径压缩
38         int tmp = findRoot(tree[x]);
39         tree[x] = tmp;
40         return tmp;
41     }
42 };

 

posted @ 2021-02-25 16:53  拾月凄辰  阅读(96)  评论(0编辑  收藏  举报