LC 速查

HOT 100索引 › B1 哈希 Hashing

LC 128最长连续序列Longest Consecutive Sequence 中等

求数组中的数字能构成的最长连续整数序列的长度,不要求原数组连续。

思路 哈希集合存全部数,只对没有前驱 x-1 的序列起点向右扩展计数,避免重复遍历。时间 O(n)。

class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        st = set(nums)
        ans = 0
        for x in st:
            if x - 1 in st:  # 只从序列起点开始
                continue
            y = x
            while y + 1 in st:
                y += 1
            ans = max(ans, y - x + 1)
        return ans
← 上一题 字母异位词分组移动零 下一题 →