给定一个未排序的整数数组,找出最长连续序列的长度。
要求算法的时间复杂度为 O(n)。
示例:
输入: [100, 4, 200, 1, 3, 2]
输出: 4
解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。
思路
利用字典哈希
1
利用dict(),以数组中每个值为key,以该值往后连续序列为value,默认为1
用i遍历数组,当i+1存在于q且q[i+1]等于1时,q[i]加一,并去掉值i+1的key
当i+1存在于q且q[i+1]不等于1时,q[i]=q[i]+q[i+1],并去掉值i+1的key
每个数组遍历3次,时间复杂度为 O(n)
2
利用set(),遍历数组中每个数,当该数是连续序列第一个数时(i-1 not in nums:)开始计算,
统计下最大的
代码
1
def longestConsecutive(self, nums):
q={}
m=0
for i in nums:
q[i]=1
for i in nums:
if i in q:
t=i
while(t+1 in q ):
t=t+1
q[i]+=q[t]
q.pop(t)
m=max(m,q[i])
return m
2
def longestConsecutive(self, nums):
nums=set(nums)
m=0
for i in nums:
if i-1 not in nums:
t=i+1
while t in nums:
t=t+1
m=max(m,t-i)
return m