128. Longest Consecutive Sequence

Обновлено: 2024-03-12
1 мин

Содержание

LeetCode problem

  1. Save all numbers in set to make it possible to get number at O(1).
  2. For each element look for the current+1 element if exists.
class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        res = 0
        nset = set(nums)

        for x in nset:
            if x - 1 not in nset: # prevent double calculations
                _max = 1
                cur = x
                while cur + 1 in nset:
                    _max += 1
                    cur += 1
                res = max(_max, res)
        return res