当前位置: 首页 > news >正文

力扣hot3--并查集+哈希

第一想法是排个序然后遍历一遍,but时间复杂度就超啦

并查集居然与哈希结合了()

已经好久没用过并查集了,,,我们用哈希表f_node中来记录原结点的父节点,其中key是原结点,value是父节点。我们用哈希表cnt来记录原结点所在集合的元素数目(只有这一集合的父节点的cnt才有效,即我们只维护父节点cnt的正确性),其中key是原结点,value是集合中元素的数目。

用哈希表来记录的好处是可以直接用.count()来查看是否存在临近元素:我们遍历nums中的每一个元素,依次判断元素值-1和元素值+1是否存在于某个集合中,如果存在,那就和元素值所在的集合合并。用res来维护最终结果。

class Solution {
public:int res=1;unordered_map<int,int> f_node;unordered_map<int,int> cnt;int find(int x){if(f_node[x]==x){return x;}f_node[x]=find(f_node[x]);return f_node[x];}void union_xy(int x,int y){int f_x=find(x);int f_y=find(y);if(f_x==f_y){return ;}f_node[f_x]=f_y;cnt[f_y]+=cnt[f_x];res=max(res,cnt[f_y]);}int longestConsecutive(vector<int>& nums) {if(nums.size()==0){return 0;}for(auto i:nums){f_node[i]=i;cnt[i]=1;}for(auto i:nums){if(f_node.count(i-1)){union_xy(i-1,i);}if(f_node.count(i+1)){union_xy(i,i+1);}}return res;}
};

简单注意一下:i 分别是nums中的数值

for(auto i:nums){if(f_node.count(i-1)){union_xy(i-1,i);}if(f_node.count(i+1)){union_xy(i,i+1);}
}

python3版本:

class Solution:res=1f_node={}cnt={}def find(self,x):if self.f_node[x]==x:return xself.f_node[x]=self.find(self.f_node[x])return self.f_node[x]def union_xy(self,x,y):f_x=self.find(x)f_y=self.find(y)if f_x==f_y:returnself.f_node[f_x]=f_yself.cnt[f_y]+=self.cnt[f_x]self.res=max(self.res,self.cnt[f_y])def longestConsecutive(self, nums: List[int]) -> int:self.res=1self.f_node={}self.cnt={}if len(nums)==0:return 0for i in nums:self.f_node[i]=iself.cnt[i]=1for i in nums:if i-1 in self.f_node:self.union_xy(i-1,i)if i+1 in self.f_node:self.union_xy(i,i+1)return self.res

看某个元素是否在列表中:直接用 in , 判断一个列表用 len() 即可

http://www.lryc.cn/news/300781.html

相关文章:

  • 微信网页版能够使用(会顶掉微信app的登陆)
  • word软件中硬件图像加速有什么用处?禁用硬件图形加速(G)会影响word文档中插入图片的分辨率吗?
  • .NET Core MongoDB数据仓储和工作单元模式封装
  • lua:有关表访问的metamethod
  • 【MySQL】索引事务
  • ChatGPT重大升级:能自动记住用户的习惯和喜好,用户有权决定是否共享数据给OpenAI
  • CSS设置盒子阴影
  • 文件夹删不掉,显示在另一个文件中打开怎么办
  • 阿里云香港云服务器租用_BGP多线网络_CN2高速线路测试
  • C# 异步方法的使用场景
  • Lua 教程
  • CleanMyMac X2024版本有哪些常见的使用场景?
  • 《Docker快速入门:从0到1构建你的第一个容器!》
  • NLP_Transformer架构
  • CVE-2012-2311 漏洞复现
  • 多线程面试题汇总
  • CentOS7.9+Kubernetes1.29.2+Docker25.0.3高可用集群二进制部署
  • STM32——OLED菜单(二级菜单)
  • 配置Vite+React+TS项目
  • 2.13:C语言测试题
  • ubuntu22.04 有一台机器说有4T硬盘,但是df的时候看不到,怎么查找
  • 【机器学习】数据清洗之识别重复点
  • 鸿蒙(HarmonyOS)项目方舟框架(ArkUI)之NavDestination组件
  • tokio tcp通信
  • LCR 122. 路径加密【简单】
  • SpringUtils 工具类,方便在非spring管理环境中获取bean
  • JavaWeb之请求
  • VsCode中常用的正则表达式操作
  • ubuntu22.04@laptop OpenCV Get Started: 007_color_spaces
  • mysql 查询性能优化关键点总结