128. 最长连续序列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0:
return 0

hashmap = set(nums) #能直接这样将数组存入set
max_len = 0

for num in hashmap:
if num - 1 not in hashmap:
cur_len = 1
cur_num = num

# 这里的while得在if里面,因为如果num-1在hashmap里的话就直接跳过num,等之后遍历到它再处理
while cur_num + 1 in hashmap:
cur_len += 1
cur_num += 1

max_len = max(max_len, cur_len)

return max_len