128. Longest Consecutive Sequence

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

For example, Given [100, 4, 200, 1, 3, 2], The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

Your algorithm should run in O(n) complexity.

Solution: HashSet

class Solution(object):
    def longestConsecutive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        max_len = 0
        nums = set(nums)
        for num in nums:
            if num - 1 not in nums:
                nxt = num + 1
                while nxt in nums:
                    nxt += 1
                max_len = max(max_len, nxt - num)
        return max_len

results matching ""

    No results matching ""