Really simple python solution with expanation


  • 0
    C

    I was clueless until my boyfriend asked, 'what's the definition of being consecutive'.
    Consecutive means it's neighbor must be in the nums. Then the idea is real simple here:

    For a unvisited number, let's check the existence of its +1 neighbor and -1 neighbor.
    For example, [100,200,4,3,5,2]
    when we have 4,

    1. check +1 neighbor which means 5, then 6, then 7... until no +1 neighbors existed
    2. check -1 neighbor which means 3, then 2, then 1...until no -1 neighbors existed
    def longestConsecutive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) == 0:
            return 0
        visited = set()
        nums = set(nums)
        result = 1
        
        for n in nums:
            curRes = 1
            if n not in visited:
                toSmall = toLarge = n
                # check to larger
                while(toLarge+1 in nums and toLarge+1 not in visited):
                    visited.add(toLarge+1)
                    toLarge +=1
                    curRes += 1
                # check to smaller
                while(toSmall-1 in nums and toSmall-1 not in visited):                    
                    visited.add(toSmall-1)
                    toSmall -=1
                    curRes += 1
                result = max(result,curRes)
        return result

Log in to reply
 

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