Leetcode128

#128. 最长连续序列

因为需要O(n)复杂度,所以每一个去暴力是不可以的。但是只有hashset不减枝也过不去。
所以需要剪枝,只对number-1不在hashset里的数字进行操作这样就能删掉很多,从而近似O(n)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
numset=set(nums)
if len(nums)>0:
maxlenth=1
else:
maxlenth=0
for i in nums:
if i-1 not in nums:
streak=1
nownum=i+1
while nownum in nums:
streak+=1
nownum+=1
maxlenth=max(streak,maxlenth)
return maxlenth