classSolution: deflongestConsecutive(self, A: List[int]) -> int: ifnot A: return0 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
classSolution: deflongestConsecutive(self, A: List[int]) -> int: ifnot A: return0 S=set(A) M=1 for a in S: if a-1notin S: k=1 i=1 while a+i in S: k+=1 i+=1 M=max(M,k) return M