0128-longest-consecutive-sequence

Try it on leetcode

Description

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

Example 3:

Input: nums = [1,0,1,2]
Output: 3

 

Constraints:

  • 0 <= nums.length <= 105
  • -109 <= nums[i] <= 109

Solution(Python)

class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        #  nums = [100,4,200,1,3,2]
        #   1 2 3 4  100 200 sort
        # 
        #   cur_lenth = 0
        #   longest_length = 0
        #   i,i + 1  : 0 , n-2
        #     if nums[i+1] - nums[i] == 1:
        #        cur_lenth += 1
        #     else:
        #        update longest_length
        #        cur_lenth = 0
        # 
        # [0,3,7,2,5,8,4,6,0,1]
        #  0 0 1 2 3 4 5 6 7 8
        #  cur_lenth = 0
        #   longest_length = 0
        #   i = 0  0 != 0  
        #   

        if not nums:
            return 0

        nums.sort()

        longest_streak = 1
        current_streak = 1

        for i in range(1, len(nums)):
            if nums[i] != nums[i - 1]:
                if nums[i] == nums[i - 1] + 1:
                    current_streak += 1
                else:
                    longest_streak = max(longest_streak, current_streak)
                    current_streak = 1

        return max(longest_streak, current_streak)
        

Dry Run