要求时间复杂度O(n)其实思路比较简单,维护一个区间的集合(用的dict),如果当前扫描的数在集合中能够与某一个区间接壤(向前或向后):合并区间
扫描当前数字
如果出现过了:不管;
如果没出现过:
如果不与集合中的区间接壤,新增新区间,起始位置为当前元素,长度为0
如果与某个区间的前边界(或/和)后边界接壤,合并此元素和区间
class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
dict_int={}
dict_head={}
dict_end={}
"""
if len(nums)<2:return len(nums)
set_int=set()
dict_head={}
dict_end={}
ans=1
for i in range(len(nums)):
if nums[i] not in set_int:
set_int.add(nums[i])
temp_a=dict_end.has_key(nums[i]-1)
temp_b=dict_head.has_key(nums[i]+1)
sum=temp_a*2+temp_b
if sum==2:
dict_head[nums[i]-1-dict_end[nums[i]-1]]+=1
dict_end[nums[i]]=temp_2=dict_end.pop(nums[i]-1)+1
ans=max(ans,temp_2+1)
elif sum==1:
dict_end[nums[i]+1+dict_head[nums[i]+1]]+=1
dict_head[nums[i]]=temp_1=dict_head.pop(nums[i]+1)+1
ans=max(ans,temp_1+1)
elif sum==0:
dict_head[nums[i]]=0
dict_end[nums[i]]=0
else:
last_len=dict_head.pop(nums[i]+1)+1
pre_len=dict_end.pop(nums[i]-1)+1
dict_head[nums[i]-pre_len]=dict_end[nums[i]+last_len]=last_len+pre_len
ans=max(ans,last_len+pre_len+1)
return ans