资讯动态

最长连续序列-哈希表128-python

发布时间:2026/10/29 10:15:04 来源:尧图企业网站定制
借助哈希表保存每个数字对应的连续序列最长长度遍历到新数字时可取出其左邻num-1、右邻num1各自记录的序列长度二者相加再加 1代表当前数字即为新序列总长。由于是连续数字构成的序列计算完成后仅需更新该序列最左端和最右端位置在哈希表中的长度值即可哈希表里已存在的数字说明已经归属序列无需重复处理。pythonclassSolution(object):deflongestConsecutive(self,nums): :type nums: List[int] :rtype: int res0num_max_length_dictdict()fornuminnums:ifnuminnum_max_length_dict:continueminus0plus0ifnum-1innum_max_length_dict:minusnum_max_length_dict[num-1]ifnum1innum_max_length_dict:plusnum_max_length_dict[num1]lengthminusplus1resmax(res,length)num_max_length_dict[num]lengthifnum-minusinnum_max_length_dict:num_max_length_dict[num-minus]lengthifnumplusinnum_max_length_dict:num_max_length_dict[numplus]lengthreturnres

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价 →
↑