泰安中文网站建设电话,有关网站建设文章,wordpress摄影主题 lens,佛山新网站建设市场第一想法是排个序然后遍历一遍#xff0c;but时间复杂度就超啦 并查集居然与哈希结合了#xff08;#xff09; 已经好久没用过并查集了#xff0c;#xff0c;#xff0c;我们用哈希表f_node中来记录原结点的父节点#xff0c;其中key是原结点#xff0c;value是父节点… 第一想法是排个序然后遍历一遍but时间复杂度就超啦 并查集居然与哈希结合了 已经好久没用过并查集了我们用哈希表f_node中来记录原结点的父节点其中key是原结点value是父节点。我们用哈希表cnt来记录原结点所在集合的元素数目只有这一集合的父节点的cnt才有效即我们只维护父节点cnt的正确性其中key是原结点value是集合中元素的数目。 用哈希表来记录的好处是可以直接用.count()来查看是否存在临近元素我们遍历nums中的每一个元素依次判断元素值-1和元素值1是否存在于某个集合中如果存在那就和元素值所在的集合合并。用res来维护最终结果。 class Solution {
public:int res1;unordered_mapint,int f_node;unordered_mapint,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_xfind(x);int f_yfind(y);if(f_xf_y){return ;}f_node[f_x]f_y;cnt[f_y]cnt[f_x];resmax(res,cnt[f_y]);}int longestConsecutive(vectorint 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(i1)){union_xy(i,i1);}}return res;}
}; 简单注意一下i 分别是nums中的数值
for(auto i:nums){if(f_node.count(i-1)){union_xy(i-1,i);}if(f_node.count(i1)){union_xy(i,i1);}
}
python3版本
class Solution:res1f_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_xself.find(x)f_yself.find(y)if f_xf_y:returnself.f_node[f_x]f_yself.cnt[f_y]self.cnt[f_x]self.resmax(self.res,self.cnt[f_y])def longestConsecutive(self, nums: List[int]) - int:self.res1self.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 i1 in self.f_node:self.union_xy(i,i1)return self.res 看某个元素是否在列表中直接用 in , 判断一个列表用 len() 即可