My simple Python solution, O(n) time using DFS


  • 1
    T

    This is a stack version of DFS.

    def longestConsecutive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
    
        nums = set(nums)
        res = 0
        while nums:
            stack = [next(iter(nums))]
            tmp = 0
            while stack:
                tmp += 1
                curr = stack.pop()
                nums.discard(curr)
                if curr + 1 in nums: stack.append(curr + 1)
                if curr - 1 in nums: stack.append(curr - 1)
            res = max(res, tmp)
        return res

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.