微软10-28下午的二面考了并查集,没写出来,羞耻
今天写3道题,省份的数量,冗余连接,打砖块
class UnionSet{
private:
int cnt;
vector<int> parent;
public:
UnionSet(int n):cnt(n){
for(int i=0;i<n;++i) parent.emplace_back(i);
}
int find(int x){
if(parent[x]!=x)
parent[x] = find(parent[x]);
return parent[x];
}
void union_two(int a, int b){
int pa = find(a);
int pb = find(b);
if(pa == pb)
return;
cnt--;
parent[pa] = pb;
}
int get_cnt(){return cnt;}
};
class Solution {
public:
int findCircleNum(vector<vector<int>>& isConnected) {
int n = isConnected.size();
UnionSet us=n;
for(int i=0;i<n;++i)for(int j=i+1;j<n;++j)if(isConnected[i][j])us.union_two(i,j);
return us.get_cnt();
}
};