class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
numlist = set(nums)
#you need set or else it's too slow
longest = 0
#the concept is you are checking to see if there is a left neighbor. If not, then there is a new sequence of conseuctive numbers.
for n in nums:
if (n - 1) not in numlist:
length = 0
while (n + length) in numlist:
length += 1
longest = max(length, longest)
return longest
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter