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

借助哈希表保存每个数字对应的连续序列最长长度;遍历到新数字时,可取出其左邻(num-1)、右邻(num+1)各自记录的序列长度,二者相加再加 1(代表当前数字),即为新序列总长。由于是连续数字构成的序列,计算完成后仅需更新该序列最左端和最右端位置在哈希表中的长度值即可;哈希表里已存在的数字说明已经归属序列,无需重复处理。

python

classSolution(object):deflongestConsecutive(self,nums):""" :type nums: List[int] :rtype: int """res=0num_max_length_dict=dict()fornuminnums:ifnuminnum_max_length_dict:continueminus=0plus=0ifnum-1innum_max_length_dict:minus=num_max_length_dict[num-1]ifnum+1innum_max_length_dict:plus=num_max_length_dict[num+1]length=minus+plus+1res=max(res,length)num_max_length_dict[num]=lengthifnum-minusinnum_max_length_dict:num_max_length_dict[num-minus]=lengthifnum+plusinnum_max_length_dict:num_max_length_dict[num+plus]=lengthreturnres