class Solution {
unordered_map<int,int>fa,rank;
void init(unordered_set
for(const auto& num:set){
fa[num]=num;
rank[num]=1;
}
}
int finds(int x){
if(x!=fa[x]){
fa[x]=finds(fa[x]);
}
return fa[x];
}
void unions(int x,int y){
int rootx=finds(x);
int rooty=finds(y);
if(rank[rootx]>rank[rooty]){
fa[rooty]=rootx;
} else if(rank[rootx]<rank[rooty]){
fa[rootx]=rooty;
} else {
fa[rootx]=rooty;
rank[rootx]++;
}
}
public:
int longestConsecutive(vector
int n=nums.size();
if(n==0) return 0;
int ans=1;
unordered_set
init(set);
for (auto& num : nums) {
if (set.count(num + 1)) { // 如果num+1存在,则合并num和num+1
unions(num, num + 1);
}
}
unordered_map<int,int>map;
for(auto&num:set){
int a=finds(num);
map[a]++;
}
for(auto&s:map){
int val=s.second;
ans=max(ans,val);
}
return ans;
}
};
标签:map,set,下标,int,查集,rank,fa,num,rootx From: https://www.cnblogs.com/zsh260439/p/18601162