0%

128. Longest Consecutive Sequence

https://leetcode.com/problems/longest-consecutive-sequence/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
def longestConsecutive(self, A: List[int]) -> int:
if not A:
return 0
S=set(A)
M=1
for a in A:
if a in S:
S.discard(a)
k=1
i=1
while a+i in S:
k+=1
S.discard(a+i)
i+=1
i=1
while a-i in S:
k+=1
S.discard(a-i)
i+=1
M=max(M,k)
return M

It can be simplified:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
def longestConsecutive(self, A: List[int]) -> int:
if not A:
return 0
S=set(A)
M=1
for a in S:
if a-1 not in S:
k=1
i=1
while a+i in S:
k+=1
i+=1
M=max(M,k)
return M