Longest Consecutive Sequence

description

accept answer(fifth try)

class Solution(object):
    def longestConsecutive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) != 0:
            count = 1
        else:
            count = 0
            return count
        nums = sorted(nums)
        print(nums)
        temp = 1
        for i in range(len(nums)):
            print("temp", temp)
            if i != len(nums)-1:
                first = nums[i]
                second = nums[i+1]
                print(first, second)
                
                if second - first == 1:
                    temp += 1
                    if temp > count:
                        count = temp
                elif second - first == 0:
                    continue
                else:
                    print("here")
                    temp = 1
           
        return count

A good answer:

class Solution(object):
    def longestConsecutive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        numSet = set(nums)
        longest = 0

        for n in nums:
            if (n - 1) not in numSet:
                length = 0
                while (n + length) in numSet:
                    length += 1
                longest = max(length, longest)
        return longest