并查集模板(map保存负数下标)

class Solution {
	unordered_map<int,int>fa,rank;
  void init(unordered_set<int>&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>& nums) {
        int n=nums.size();
        if(n==0) return 0;
        int ans=1;
        unordered_set<int>set(nums.begin(),nums.end());
        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;
        
        
    }
};
posted @   Qacter  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示