LeetCode 128 Longest Consecutive Sequence (Python)

Posted by 小明MaxMing on October 12, 2024

题目

Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.

You must write an algorithm that runs in O(n) time.

解题思路

代码

class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        s = set(nums)
        res = 0
        for n in nums:
            if n - 1 in s:
                continue
            cur = n + 1
            while cur in s:
                cur += 1
            res = max(res, cur - n)
        return res

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅