Leetcode 128. Longest Consecutive Sequence (Python)

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

You must write an algorithm that runs in O(n) time.

Example 1:

Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

Example 2:

Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9

Constraints:

  • 0 <= nums.length <= 105
  • -109 <= nums[i] <= 109
class Solution(object):
    def longestConsecutive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums = list(set(nums))
        nums.sort()
        if nums == []:
            return 0
        
        if len(nums) == 2 and nums[1] - nums[0] == 1:
            return 2
        elif len(nums) == 2 and nums[1] - nums[0] != 1:
            return 1
        
        if len(nums) == 1:
            return 1
        
        lst = []
        for i in range(len(nums)-1):
            cha = nums[i+1] - nums[i]
            lst.append(cha)
            
        print(nums)
        print(lst)
            
        lst1 = []
        temp = 0
        for j in lst:
            if j == 1:
                temp += 1
                lst1.append(temp)
            else:
                temp = 0
                
        if lst1 == []:
            return 1
        
        return max(lst1) + 1


版权声明:本文为weixin_58080442原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。